Mybatis用注解实现CRUD、这里只作具体的实现过程。前期创建项目等工作不再介绍。
一、我们首先可以在工具类创建的时候实现自动提交事务。
package com.wst.utils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
public class MyBatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try{
//使用mybatis第一步、获取sqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}catch(IOException e) {
e.printStackTrace();
}
}
//返回sqlsession对象
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession(true);
}
}
二、编写接口,并增加注解。
package com.wst.dao;
import com.wst.pojo.Stu;
import org.apache.ibatis.annotations.*;
import java.util.List;
public interface StuMapper {
//查找学生全部信息
@Select(value = "select * from stu")
List<Stu> getStus();
//根据id查找学生的信息
//方法存在多个参数,所有的参数前面必须加上@Param注解
@Select("select * from stu where id = #{id}")
Stu getStuByID(@Param("id")int id);
//插入学生信息
@Insert("insert into stu(id,name,age,add) values (#{id},#{name},#{age},#{add})")
int addStu(Stu stu);
//更改学生信息
@Update("update stu set name = #{name},age = #{age}, add=#{add} where id = #{id}")
int updateStu(Stu stu);
//删除学生信息
@Delete("delete from stu where id = #{id}")
int deleteStu(@Param("id") int id);
}
三、在Mybatis的核心配置文件中,绑定接口。
<mappers>
<mapper class="com.wst.dao.StuMapper" />
</mappers>
四、编写测试类、进行测试。
public class StuMapperTest {
@Test
public void test(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
StuMapper mapper = sqlSession.getMapper(StuMapper.class);
//查找学生的全部信息
List<Stu> stuList = mapper.getStus();
for (Stu stu : stuList) {
System.out.println(stu);
}
//根据学生的id查询学生的信息
Stu stuByID = mapper.getStuByID(1);
System.out.println(stuByID);
//增加学生信息
mapper.addStu(new Stu(12,"张三",12,"陕西"));
//更改学生信息
mapper.updateStu(new Stu(12,"张三",13,"陕西"));
//删除学生信息
mapper.deleteStu(12);
sqlSession.close();
}