1.mapper.xml
在config下新建sqlmap包,包中新建User.xml
<mapper namespace="test">
<select id="findeUserById" parameterType="int" resultType="com.chinglee.ssm.po.User">
SELECT * FROM USER WHERE id=#{value}
</select>
</mapper>
2. Sqlmapconfig中加载xml文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org/DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--加载映射文件-->
<mappers>
<mapper resource="sqlmap/User.xml"/>
<!--批量加载mapper
指定mapper接口的包名,mybatis自动扫描包下面所有mapper接口进行加载
遵循一些规范:需要将mapper接口类名和mapper.xml映射文件名称保持一致,且在一个目录中
前提:使用mapper代理的方法
-->
<!-- <package name="com.chinglee.mybatis.mapper"/>-->
</mappers>
</configuration>
3.DAO接口
4.DAO接口实现类
- dao接口实现类需要注入SqlSessionFactory,通过spring进行注入。
这里spring声明配置方式,配置dao的bean:
在applicationContext.xml中配置
<!--原始dao接口-->
<bean id="userDao" class="com.chinglee.ssm.dao.UserDaoImpl">
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
- 让UserDaoImpl实现类继承SqlSessionDaoSupport
package com.chinglee.ssm.dao;
import com.chinglee.ssm.po.User;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.support.SqlSessionDaoSupport;
/**
* Created by Administrator on 2017/11/2 0002.
*/
public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao {
@Override
public User findUserById(int id) throws Exception {
//继承SqlSessionDaoSupport,通过this.getSqlSession()得到sqlSession
SqlSession sqlSession=this.getSqlSession();
User user=sqlSession.selectOne("test.findUserById",id);
return user;
}
}
5.测试
package com.chinglee.ssm.dao;
import com.chinglee.ssm.po.User;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Created by Administrator on 2017/11/2 0002.
*/
public class UserDaoImplTest {
private ApplicationContext applicationContext;
//在setUp方法得到spring容器
@Before
public void setUp() throws Exception {
applicationContext=new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
}
@Test
public void findUserById() throws Exception {
UserDao userDao= (UserDao) applicationContext.getBean("userDao");
User user=userDao.findUserById(1);
System.out.println(user);
}
}