Mybatis与Spring的整合

1、导入jar包

2、创建SqlMapConfig文件








3、创建User.xml映射文件





4、创建Spring的配置文件



<context:property-placeholder location="classpath:db.properties" />















5、接口文件

public interface UserDao {
public User findUser(int id) throws Exception;
}

6、接口实现

public class UserImple extends SqlSessionDaoSupport implements UserDao {

public User findUser(int id) throws Exception {
SqlSession session = this.getSqlSession();
User user = session.selectOne("findUser",id);
return user;
}

}

7、测试代码

public class Test {

private ApplicationContext applicationContext;

@Before
public void setUp() throws Exception{
applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

}
@org.junit.Test
public void testFindUserById() throws Exception{
UserDao userDao = (UserDao) applicationContext.getBean("userImpl");
User user = userDao.findUser(1);
System.out.println(user);
}

}

8、使用Mapper代理开发方式

1、通过MapperFactoryBean创建代理对象

(1)Mapper.xml和mapper接口文件保持不变
(2)Spring配置文件如下:






(3)测试代码:

public void testFindUserById1() throws Exception{
Mapper mapper = (Mapper) applicationContext.getBean("userMapper");
User user = mapper.findUser(1);
System.out.println(user);
}
(4)缺点:每一个mapper都要件bean配置,过于麻烦。

2、通过MapperScannerConfigurer进行mapper扫描(建议使用)

(1)Mapper.xml和mapper接口文件保持不变
(2)如果将mapper.xml和mapper接口的名称保持一致且放在一个目录 则不用在sqlMapConfig.xml中进行配置。
(3)Spring配置文件如下:







(4)测试代码:

public void testFindUserById2() throws Exception{
Mapper mapper = (Mapper) applicationContext.getBean("mapper");
User user = mapper.findUser(1);
System.out.println(user);
}

posted @ 2017-07-30 22:12  一条路上的咸鱼  阅读(167)  评论(0)    收藏  举报