認識mybatis-spring
MyBatis-Spring 需要以下版本:
,
如果使用 Maven 作為構建工具,僅需要在 pom.xml 中加入以下代碼即可:
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.2</version>
</dependency>
整合實作一:
1.引入spring組態檔beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
2.配置資料源替換mybatis的資料源
<!--配置資料源:資料源有非常多,可以使用第三方的,也可使使用Spring的-->
<bean id="dataSource">
<property name="driverClassName" value="https://www.cnblogs.com/xsc1234/p/com.mysql.jdbc.Driver"/>
<property name="url" value="https://www.cnblogs.com/xsc1234/p/jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=utf8"/>
<property name="username" value="https://www.cnblogs.com/xsc1234/p/root"/>
<property name="password" value="https://www.cnblogs.com/xsc1234/p/123456"/>
</bean>
3.配置sqlsessionfactory,關聯mybatis
<!--配置SqlSessionFactory-->
<bean id="sqlSessionFactory" >
<property name="dataSource" ref="dataSource"/>
<!--關聯Mybatis-->
<property name="configLocation" value="https://www.cnblogs.com/xsc1234/p/classpath:mybatis-config.xml"/>
<property name="mapperLocations" value="https://www.cnblogs.com/xsc1234/p/classpath:com/kuang/dao/*.xml"/>
</bean>
4.注冊SQL sessiontemplate,關聯sqlsessionfactory
<!--注冊sqlSessionTemplate , 關聯sqlSessionFactory-->
<bean id="sqlSession" >
<!--利用構造器注入-->
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
5.增加dao介面的實作類:私有化sqlsessiontemplate
public class UserDaoImpl implements UserMapper {
//sqlSession不用我們自己創建了,Spring來管理
private SqlSessionTemplate sqlSession;
public void setSqlSession(SqlSessionTemplate sqlSession) {
this.sqlSession = sqlSession;
}
public List<User> selectUser() {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
return mapper.selectUser();
}
}
6.注冊bean實作
<bean id="userDao" >
<property name="sqlSession" ref="sqlSession"/>
</bean>
7.測驗
@Test
public void test2(){
ApplicationContext context = newClassPathXmlApplicationContext("beans.xml");
UserMapper mapper = (UserMapper) context.getBean("userDao");
List<User> user = mapper.selectUser();
System.out.println(user);
}
整合方式二:
mybatis-spring1.2.3版以上的才有這個 .
官方檔案截圖 :
dao繼承Support類 , 直接利用 getSqlSession() 獲得 , 然后直接注入SqlSessionFactory . 比起方式1 , 不需要管理SqlSessionTemplate , 而且對事務的支持更加友好 . 可跟蹤原始碼查看

1.實作類繼承sqlsessiondaosupport
public class UserDaoImpl extends SqlSessionDaoSupport implements UserMapper {
public List<User> selectUser() {
UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
return mapper.selectUser();
}
}
2.修改bean配置
<bean id="userDao" >
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
//可以不用注冊sqlsessiontemplate
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/108172.html
標籤:Java
上一篇:Java8 新特性
