标签:throws void set new 大量 .com public insert test
public interface UserDao { // 一般会把异常抛出 public User getUserById(int id) throws Exception; public void insertUser(User user) throws Exception; }
实现类
package com.lhx.mybatis.olddaomybatis; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import com.lhx.mybatis.po.User; public class UserDaoImpl implements UserDao { private SqlSessionFactory sqlSessionFactory; public SqlSessionFactory getSqlSessionFactory() { return sqlSessionFactory; } public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) { this.sqlSessionFactory = sqlSessionFactory; } //注入SqlSessionFactory public UserDaoImpl(SqlSessionFactory sqlSessionFactory){ this.setSqlSessionFactory(sqlSessionFactory); } public void insertUser(User user) throws Exception { SqlSession sqlSession = sqlSessionFactory.openSession(); try { sqlSession.insert("test.insertUser", user); sqlSession.commit(); } finally{ sqlSession.close(); } } public User getUserById(int id) throws Exception { SqlSession session = sqlSessionFactory.openSession(); User user = null; try { //通过sqlsession调用selectOne方法获取一条结果集 //参数1:指定定义的statement的id,参数2:指定向statement中传递的参数 user = session.selectOne("test.findUserById", 1); System.out.println(user); } finally{ session.close(); } return user; } }
测试代码
public class TestDao { // 会话工厂 private SqlSessionFactory sqlSessionFactory; @Before public void setUp() throws Exception { // 配置文件 String resource = "SqlMapConfig.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); // 使用SqlSessionFactoryBuilder从xml配置文件中创建SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } @Test public void testFindUserById() throws Exception { UserDao userDao = new UserDaoImpl(sqlSessionFactory); User user = userDao.getUserById(1); System.out.println(user); } }
java-mybaits-00202-DAO-原始DAO开发方法
标签:throws void set new 大量 .com public insert test
原文地址:http://www.cnblogs.com/bjlhx/p/6819034.html