ssm-spring集成mybatis
MyBatis-Spring簡介
MyBatis-Spring是一個依賴庫,可以無縫的將MyBatis整合到Spring中,該庫可以讓MyBatis參與到Spring事務管理中,可以負責mapper和SqlSession的創建和注入, 可以將MyBatis中的例外轉換為Spring的DataAccessException,最終讓你構建的工程代碼脫離MyBatis,Spring和MyBatis-Spring的依賴,
快速開始
- 匯入依賴: 首先在pom.xml檔案中,匯入以下配置:
- 配置資料源:
- 配置SqlSessionFactory: 在之前的mybatis中提到過,使用MybatisUtils工具類來封裝SqlSession相關物件的構建,而現在我們將在Spring application context中對這些物件進行配置注入,
- 配置Mapper:
- 撰寫測驗:
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.10</version>
</dependency>
<!--配置資料源,可以是實作了javax.sql.DataSource介面的任意資料源,這里使用MysqlDataSource-->
<bean id="dataSource" >
<property name="url" value="https://www.cnblogs.com/zhoux123/p/jdbc:mysql://xxx"/>
<property name="user" value="https://www.cnblogs.com/zhoux123/p/資料庫用戶名"/>
<property name="password" value="https://www.cnblogs.com/zhoux123/p/資料庫密碼"/>
</bean>
<!--1、SqlSessionFactoryBean:實作了介面org.springframework.beans.factory.FactoryBean-->
<!--2、SqlSessionFactory:通過SqlSessionFactoryBean物件的getObject()方法來構建-->
<!--3、dataSource和mapperLocations:getObject()方法中創建SqlSessionFactory物件的屬性-->
<bean id="sqlSessionFactory" >
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations" value="https://www.cnblogs.com/zhoux123/p/classpath*:com/zx/demo/mybatis/**/*.xml"/>
</bean>
<!--1、MapperFactoryBean:實作了介面org.springframework.beans.factory.FactoryBean-->
<!--2、StudentMapper:通過MapperFactoryBean物件的getObject()方法來構建-->
<!--3、mapperInterface和sqlSessionFactory:getObject()方法中創建StudentMapper介面代理實作物件的屬性-->
<bean id="exampleMapper" >
<property name="mapperInterface" value="https://www.cnblogs.com/zhoux123/p/com.zx.demo.mybatis.spring.mapper.StudentMapper"/>
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
public class MybatisTest {
@Test
public void test() throws Exception {
ApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml");
StudentMapper mapper = (StudentMapper) context.getBean("exampleMapper");
List<Map<Object, Object>> maps = mapper.queryAll();
for (Map<Object, Object> map : maps) {
for (Object o : map.keySet()) {
System.out.println(o.toString() + ":" + map.get(o));
}
System.out.println("===");
}
}
}
工程結構如下:
現在運行測驗結果如下:

更多
更多詳細進階配置,請參考官網
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/356010.html
標籤:Java
上一篇:全面通透深入剖析工廠方法模式
