#整合MyBatis ##SqlSessionFactory 在通常的數據庫項目當中,咱們須要構建SqlSessionFactoryBuilder,獲取session,在使用MyBatis的session API去操做數據庫。java
在Spring中,MyBatis提供了SqlSessionFactoryBean來整合MyBatis所提供的功能spring
##添加mybatis-spring依賴sql
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.0</version> </dependency>
除了Mybatis-Spring還要添加MyBatis自己的依賴數據庫
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.1</version> </dependency>
##在Spring配置中定義SqlSessionFactoryBeanapache
<!-- MyBatis --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" > <property name="dataSource" ref="dataSource" /> </bean>
以下方式執行配置文件,分別制定configLocation和mapperLocations編程
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" > <property name="dataSource" ref="dataSource" /> <property name="configLocation" value="classpath:sqlMapConfig.xml" /> <property name="mapperLocations" value="classpath*:sample/config/mappers/**/*.xml" /> </bean>
##Annotation定義Mapper - 註解 經過Annotation方式聲明接口,接口與查詢分開session
public interface UserMapper { @Select("SELECT * FROM users WHERE id = #{userId}") User getUser(@Param("userId") String userId); }
##XML方式定義Mappermybatis
public interface UserMapper{ User getUser(String userId); }
對應的mapper定義app
<mapper namespace="com.netease.course.UserMapper"> <select id="getUser" resultType="User"> SELECT * FROM users WHERE id = #{userId} </select> </mapper>
通常狀況下,本身的項目更傾向於Annotation方式來定義Mapper,不用多XML文件,項目看起來更乾淨。
定義完畢Mapper,要告訴Spring註冊成爲Beanui
##定義Mapper Bean Mapper Bean能夠理解成DAO,完成的工做就是CRUD,均可以定義在Mapper裏面。 ###經過XML配置文件方式 須要制定MapperFactoryBean的Class,須要這個類把接口轉換成Bean。屬性有聲明接口
實際項目當中,會有不少Mapper
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> <property name="mapperInterface" value="com.netease.course.MybatisUserDao" /> <property name="sqlSessionFactory" ref="sqlSessionFactory" /> </bean>
###自動發現機制Mapper 須要添加額外配置, 須要定義mybatis的tag,xmlns:mybatis="http://mybatis.org/schema/mybatis-spring"
,而後填寫對應xsd,添加自動掃描的包名稱
<mybatis:scan base-package="com.netease.course" />
通常狀況下,咱們不須要執行sqlSessionFactory,默認會自動注入,可是若是多個數據源定義了不一樣的SqlSessionFactory,則按照以下進行配置
<mybatis:scan base-package="com.netease.course" factory-ref="sqlSessionFactory" />
###另一種自動發現機制
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.netease.course" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> </bean>
##使用與注入Mapper 能夠經過Autowired Annotation進行注入使用。這樣咱們能夠直接使用預約義好的方法,能夠把SQL封裝好。可是並無把session相關的接口暴露出來,執行邏輯都封裝掉了。但咱們有時候須要更細緻的控制。
public class SomeService{ @Autowired private UserMapper userMapper; }
##SqlSessionTemplate
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg index="0" ref="sqlSessionFactory" /> </bean>
public class UserDao { @Autowired Private SqlSession sqlSession; public User getUSer(String userId) { return (User) sqlSession.selectOne("com.netease.course.UserMapper.getUser",userId); } }
##MyBatis與Spring事務管理整合
##實際整合MyBatis 接口
package com.hava.spring_data.repository; import com.hava.spring_data.entity.User; import org.apache.ibatis.annotations.Select; import java.util.List; /** * Created by yanfa on 2016/10/26. */ public interface MyBatisDao { @Select("SELECT * FROM user WHERE first_name= #{firstName}") public User findOne(String firstName); @Select("SELECT * FROM user") public List<User> findAll(); }
配置
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mybatis="http://mybatis.org/schema/mybatis-spring" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.xsd"> <!-- 數據源配置 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driverClassName}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </bean> <context:property-placeholder location="db.properties" /> <!-- MyBatis --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" > <property name="dataSource" ref="dataSource" /> <!--<property name="configLocation" value="classpath:sqlMapConfig.xml" />--> <!--<property name="mapperLocations" value="classpath*:sample/config/mappers/**/*.xml" />--> </bean> <!--<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">--> <!--<property name="mapperInterface" value="com.netease.course.MybatisUserDao" />--> <!--<property name="sqlSessionFactory" ref="sqlSessionFactory" />--> <!--</bean>--> <mybatis:scan base-package="com.hava.spring_data.repository" /> </beans>
運行類
package com.hava.spring_data; import com.hava.spring_data.entity.User; import com.hava.spring_data.repository.MyBatisDao; import org.springframework.context.ApplicationContext; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * Created by yanfa on 2016/10/26. */ public class MyBatisSpringMain { public static void main(String [] args){ ApplicationContext context = new ClassPathXmlApplicationContext("mybatis-context.xml"); MyBatisDao myBatisDao = context.getBean("myBatisDao",MyBatisDao.class); for(User user : myBatisDao.findAll()) System.out.println(user.getFirst_name() + " " + user.getLast_name()); User user = myBatisDao.findOne("Zhan"); System.out.println(user.getId() + ":" + user.getFirst_name() + " " + user.getLast_name()); ((ConfigurableApplicationContext) context).close(); } }
運行結果
Meimie Han Lei Li Meimie Han Lei Li Zhan Peng 7:Zhan Peng
##須要添加映射Annotation 若是在查詢以後,一些值爲空,說明實際的數據庫列與對象屬性沒法進行對應,這個時候須要添加@Results的註解來進行映射
@Results({ @Result(property = "id",column = "id"), @Result(property = "firstName",column = "first_name"), @Result(property = "lastName",column = "last_name"), }) @Select("SELECT * FROM user") public List<BigUser> getUserList();
注意:@Results是進行的對象映射,並不針對是不是List,也就是說findOne也是這樣映射的。