Spring集成MyBatis框架
阿新 • • 發佈:2017-10-04
rollback epo 3.0 -c group utf mybatis框架 tor 編輯
(一).MyBatis介紹
MyBatis 是一款優秀的持久層框架,它支持定制化 SQL、存儲過程以及高級映射。MyBatis 避免了幾乎所有的 JDBC 代碼和手動設置參數以及獲取結果集。
創建MyBatis SQL映射XML文件:MyBatis Generator配置示例
MyBatis配置,創建resources/mybatis/mybatis.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> <settings> <setting name="lazyLoadingEnabled" value="false"/> <!-- 設置mybatis內置日誌工廠 --> <setting name="logImpl" value="LOG4J"/> <!-- 支持Null值(value)輸出Key --> <setting name="callSettersOnNulls" value="true"/> </settings> </configuration>
Maven導入MyBatis相關依賴,編輯pom.xml
<!-- 導入database依賴,使用druid作連接池 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.3</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.44</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.1</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.3.10.RELEASE</version> </dependency>
(二).方法一(通過MapperScannerConfigurer實現,直接對Mapper接口進行代理)
數據庫相關bean對象配置,創建resources/spring/applicationContext_database.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"> <!-- 引入配置文件 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:/mybatis/db.properties"/> </bean> <!-- dataSource配置 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" 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}"/> <property name="filters" value="log4j"/> <property name="maxActive" value="5"/> <property name="initialSize" value="1"/> <property name="maxWait" value="6000"/> </bean> <!-- mybatis文件配置,mapper.xml文件掃描 --> <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="configLocation" value="classpath:/mybatis/mybatis.xml"/> <property name="mapperLocations" value="classpath:/mybatis/*Mapper.xml"/> <property name="dataSource" ref="dataSource"/> </bean> <!-- mapper註解掃描器配置,掃描@MapperScan註解,自動生成代碼對象 --> <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.learn.spring.server.dao"/> <property name="sqlSessionFactoryBeanName" value="sessionFactory"/> </bean> </beans>
UserDOMapper添加註解@MapperScan,編輯dao/UserDOMapper.java
/** * 接口中的方法名稱要和對應的MyBatis映射文件中的語句的id值一樣 */ @MapperScan public interface UserDOMapper { int deleteByPrimaryKey(Integer id); int insert(UserDO record); int insertSelective(UserDO record); UserDO selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(UserDO record); int updateByPrimaryKey(UserDO record); }
(三).方法二(繼承SqlSessionDaoSupport,並實現SqlSession接口)
數據庫相關bean對象配置,創建resources/spring/applicationContext_database.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"> <!-- 引入配置文件 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:/mybatis/db.properties"/> </bean> <!-- dataSource配置 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" 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}"/> <property name="filters" value="log4j"/> <property name="maxActive" value="5"/> <property name="initialSize" value="1"/> <property name="maxWait" value="6000"/> </bean> <!-- mybatis配置,mapper.xml文件掃描 --> <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="configLocation" value="classpath:/mybatis/mybatis.xml"/> <property name="mapperLocations" value="classpath:/mybatis/mapper/*Mapper.xml"/> <property name="dataSource" ref="dataSource"/> </bean> </beans>
繼承SqlSessionDaoSupport,並實現SqlSession接口,創建dao/impl/BaseDaoImpl.java
public class BaseDaoImpl extends SqlSessionDaoSupport implements SqlSession { @Override @Resource public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) { super.setSqlSessionFactory(sqlSessionFactory); } public <T> T selectOne(String s) { return getSqlSession().selectOne(s); } public <T> T selectOne(String s, Object o) { return getSqlSession().selectOne(s, o); } public <E> List<E> selectList(String s) { return getSqlSession().selectList(s); } public <E> List<E> selectList(String s, Object o) { return getSqlSession().selectList(s, o); } public <E> List<E> selectList(String s, Object o, RowBounds rowBounds) { return getSqlSession().selectList(s, o, rowBounds); } public <K, V> Map<K, V> selectMap(String s, String s1) { return getSqlSession().selectMap(s, s1); } public <K, V> Map<K, V> selectMap(String s, Object o, String s1) { return getSqlSession().selectMap(s, o, s1); } public <K, V> Map<K, V> selectMap(String s, Object o, String s1, RowBounds rowBounds) { return getSqlSession().selectMap(s, o, s1, rowBounds); } public <T> Cursor<T> selectCursor(String s) { return getSqlSession().selectCursor(s); } public <T> Cursor<T> selectCursor(String s, Object o) { return getSqlSession().selectCursor(s, o); } public <T> Cursor<T> selectCursor(String s, Object o, RowBounds rowBounds) { return getSqlSession().selectCursor(s, o, rowBounds); } public void select(String s, Object o, ResultHandler resultHandler) { getSqlSession().select(s, o, resultHandler); } public void select(String s, ResultHandler resultHandler) { getSqlSession().select(s, resultHandler); } public void select(String s, Object o, RowBounds rowBounds, ResultHandler resultHandler) { getSqlSession().select(s, o, rowBounds, resultHandler); } public int insert(String s) { return getSqlSession().insert(s); } public int insert(String s, Object o) { return getSqlSession().insert(s, o); } public int update(String s) { return getSqlSession().update(s); } public int update(String s, Object o) { return getSqlSession().update(s, o); } public int delete(String s) { return getSqlSession().delete(s); } public int delete(String s, Object o) { return getSqlSession().delete(s, o); } public void commit() { getSqlSession().commit(); } public void commit(boolean b) { getSqlSession().commit(b); } public void rollback() { getSqlSession().rollback(); } public void rollback(boolean b) { getSqlSession().rollback(b); } public List<BatchResult> flushStatements() { return getSqlSession().flushStatements(); } /** * 實現空方法,SqlSession由Spring管理並關閉,如果手工關閉,則會拋異常 * java.lang.UnsupportedOperationException: Manual close is not allowed over a Spring managed SqlSession */ public void close() { } public void clearCache() { getSqlSession().clearCache(); } public Configuration getConfiguration() { return getSqlSession().getConfiguration(); } public <T> T getMapper(Class<T> aClass) { return getSqlSession().getMapper(aClass); } public Connection getConnection() { return getSqlSession().getConnection(); } }
繼承BaseDaoImol,並實現UserDOMapper接口,創建dao/impl/UserDaoImpl.java
@Repository public class UserDaoImpl extends BaseDaoImpl implements UserDOMapper { public int deleteByPrimaryKey(Integer id) { return delete("com.learn.spring.server.dao.UserDOMapper.deleteByPrimaryKey", id); } public int insert(UserDO record) { return insert("com.learn.spring.server.dao.UserDOMapper.insert", record); } public int insertSelective(UserDO record) { return insert("com.learn.spring.server.dao.UserDOMapper.insertSelective", record); } public UserDO selectByPrimaryKey(Integer id) { return selectOne("com.learn.spring.server.dao.UserDOMapper.selectByPrimaryKey", id); } public int updateByPrimaryKeySelective(UserDO record) { return update("com.learn.spring.server.dao.UserDOMapper.updateByPrimaryKeySelective", record); } public int updateByPrimaryKey(UserDO record) { return update("com.learn.spring.server.dao.UserDOMapper.updateByPrimaryKey", record); } }
(四).調用示例
Spring框架直接註入UserDOMapper,創建service/UserService.java
@Service public class UserServiceImpl implements UserService { @Resource private UserDOMapper userDao; public UserDO get(Integer id) { return userDao.selectByPrimaryKey(id); } }
Spring集成MyBatis框架