1.mapper.xml
在config下新建sqlmap包,包中新建User.xml
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自動(dòng)掃描包下面所有mapper接口進(jìn)行加載
遵循一些規(guī)范:需要將mapper接口類名和mapper.xml映射文件名稱保持一致创泄,且在一個(gè)目錄中
前提:使用mapper代理的方法
-->
<!-- <package name="com.chinglee.mybatis.mapper"/>-->
</mappers>
</configuration>
3.DAO接口
DAO接口
4.DAO接口實(shí)現(xiàn)類
- dao接口實(shí)現(xiàn)類需要注入SqlSessionFactory,通過spring進(jìn)行注入括蝠。
這里spring聲明配置方式鞠抑,配置dao的bean:
在applicationContext.xml中配置
<!--原始dao接口-->
<bean id="userDao" class="com.chinglee.ssm.dao.UserDaoImpl">
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
- 讓UserDaoImpl實(shí)現(xiàn)類繼承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);
}
}