public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao{
public User findUserById(int id) throws Exception { //继承SqlSessionDaoSupport类,通过this.getSqlSession()得到sqlSession SqlSession sqlSession=this.getSqlSession();
User user=sqlSession.selectOne("test.findUserById",id);
//注解Before是在执行本类所有测试方法之前先调用这个方法 @Before public void setup() throws Exception{ applicationContext=new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
}
@Test public void testFindUserById() throws Exception{ UserDao userDao=(UserDao)applicationContext.getBean("userDao");
//调用UserDao的方法 User user=userDao.findUserById(1); //输出用户信息 System.out.println(user.getId()+":"+user.getUsername()); }
}
测试结果和输出日志:
DEBUG [main] - Creating a new SqlSession DEBUG [main] - SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@8dcd5d] was not registered for synchronization because synchronization is not active DEBUG [main] - Fetching JDBC Connection from DataSource DEBUG [main] - JDBC Connection [jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8, UserName=root@localhost, MySQL-AB JDBC Driver] will not be managed by Spring DEBUG [main] - ==> Preparing: SELECT * FROM USER WHERE id=? DEBUG [main] - ==> Parameters: 1(Integer) DEBUG [main] - DEBUG [main] - Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@8dcd5d] DEBUG [main] - Returning JDBC Connection to DataSource 1:张明明
5.mapper代理开发
5.1mapper.xml和mapper.java
UserMapper.xml:
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
UserMapper.java:
package cn.edu.hpu.ssm.mapper;
import cn.edu.hpu.ssm.po.User;
//用户管理的Dao接口 public interface UserMapper {
//根据Id查询用户信息 public User findUserById(int id) throws Exception; }
//注解Before是在执行本类所有测试方法之前先调用这个方法 @Before public void setup() throws Exception{ applicationContext=new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
}
@Test public void testFindUserById() throws Exception { UserMapper userMapper=(UserMapper)applicationContext.getBean("userMapper"); User user=userMapper.findUserById(1); System.out.println(user.getId()+":"+user.getUsername());
}
}
测试结果及输出日志:
DEBUG [main] - Returning cached instance of singleton bean 'userMapper' DEBUG [main] - Creating a new SqlSession DEBUG [main] - SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@13b5a3a] was not registered for synchronization because synchronization is not active DEBUG [main] - Fetching JDBC Connection from DataSource DEBUG [main] - JDBC Connection [jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8, UserName=root@localhost, MySQL-AB JDBC Driver] will not be managed by Spring DEBUG [main] - ==> Preparing: SELECT * FROM USER WHERE id=? DEBUG [main] - ==> Parameters: 1(Integer) DEBUG [main] - DEBUG [main] - Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@13b5a3a] DEBUG [main] - Returning JDBC Connection to DataSource 1:张明明