一、原生原理
1.dao层接口
public interface UserDao {
public User selectById(int id);
}
2.实体类
public class User {
private Integer id;
private String name;
private String password;
}
3.Mapper.xml
<!--UserMapper.xml相当于UserDao接口实现类 namespace:关联指定接口-->
<!-- select:表示里面的sql语句为查询,id:关联方法
resultType:返回值类型
#{id}: id名和方法参数的名称一致
-->
<mapper namespace="com.qf.dao.UserDao">
<select id="selectById" resultType="com.qf.entity.User">
select * from user where id=#{id}
</select>
</mapper>
4.测试类
这是最初开始时获取导dao层执行对象的方法
@Test
public void selectById() throws IOException {
//从资源目录中得到mybatis-config.xml的资源
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
//根据mybatis资源,得到SqlSessionFactory对象
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
//根据工厂获取连接对象SqlSession
SqlSession sqlSession = factory.openSession();
//根据连接对象得到UserDao执行对象
UserDao mapper = sqlSession.getMapper(UserDao.class);
//对dao层方法的调用进行测试
User user = mapper.selectById(1);
System.out.println(user);
}
这是封装为工具类之后的
//共享的数据工厂
private static SqlSessionFactory factory;
//根据导入日志以及输出的日志判断
//mybatis中使用了事务,要保证事务与dao连接的对象是同一个所以需要ThreadLocal管理
private final static ThreadLocal<SqlSession> TH=new ThreadLocal();
//静态代码块
static {
try {
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
factory = new SqlSessionFactoryBuilder().build(is);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession openSession(){
SqlSession session=TH.get();
//对连接对象为null与否进行判断
if (session==null){
session=factory.openSession();
TH.set(session);//存储session对象,方便之后在使用过程中进行调用
}
return session;
}
//使用泛型
//使用泛型的方法可以保证,当我们在测试层调用该方法时,传入的实体对象是谁,就能得到对应的实体
public static <T> T getMapper(Class<T> cla){
SqlSession session=openSession();
return session.getMapper(cla);
}
public static void commit(){
SqlSession session=openSession();
session.commit();//事务的提交
closeAll();//事务的关闭
}
public static void rollback(){
SqlSession session=openSession();
session.rollback();//事务的回滚
closeAll();//事务的关闭
}
private static void closeAll(){//用于关闭session
SqlSession session=openSession();
session.close();//对session进行关闭
TH.remove();//移除ThreadLocal里面的session
}
public static SqlSession getSession(){
return factory.openSession();
}