mybatis(四)_原始dao开发方法(dao接口和dao实现类)

一. 前言:SqlSession使用范围:
  1. SqlSessionFactoryBuilder:工具类
  2. SqlSessionFactory:单例模式
  3. SqlSession:
  • 线程不安全:在SqlSesion实现类中除了有操作数据库的方法,还有数据域属性
  • 最佳应用场合:方法,定义成局部变量
二. 实现步骤:

思路:
编写dao接口和dao实现类;
向dao实现类中注入SqlSessionFactory;
在方法体内通过SqlSessionFactory创建SqlSession

1.po类创建:
public class User {
	private int id;
	private String username;
	private String sex;
	private Date birthday;
	private String address;
	}
2.xml文件Sql语句编写:
<mapper namespace="test">
	<select id="findById" parameterType="int" resultType="cn.itcast.mybatis.po.User">
		select * from user where id=#{id}
	</select>
</mapper>
3.SqlMapConfig.xml配置
<mapper resource="Sqlmap/User.xml"/> </mappers>
4.创建dao接口:
public interface UserDao {
	public User findUserById (int id);
}
5.dao接口实现类:
public class UserDaoImpl  implements UserDao {

	private SqlSessionFactory sqlSessionFactory;
	
	public UserDaoImpl(SqlSessionFactory sqlSessionFactory)
	{
	  this.sqlSessionFactory=sqlSessionFactory;	
	}
	
	@Override
	public User findUserById(int id) {
		SqlSession sqlSession=sqlSessionFactory.openSession();
		User user=sqlSession.selectOne("test.findById", 1);	
		return user;		
	}

}
6.测试代码:
public class UserDaoImplTest {

	private SqlSessionFactory sqlSessionFactory;

	@Before
	public void setup() throws IOException {
		String resource = "SqlMapConfig.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
	}

	@Test
	public void testFindUserById() throws IOException {

		UserDao userDao = new UserDaoImpl(sqlSessionFactory);

		User user = userDao.findUserById(1);

		System.out.print(user);
	}

}
三. 缺点总结:
  1. dao接口实现类存在大量模板方法;
  2. dao接口实现类statement的id硬编码;
  3. sqlsession方法使用泛型,无法校验传入参数类型
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值