目前大部分的 Java 互聯網項目,都是用 Spring MVC + Spring + MyBatis 搭建平臺的。java
使用 Spring IoC 能夠有效的管理各種的 Java 資源,達到即插即拔的功能;經過 Spring AOP 框架,數據庫事務能夠委託給 Spring 管理,消除很大一部分的事務代碼,配合 MyBatis 的高靈活、可配置、可優化 SQL 等特性,徹底能夠構建高性能的大型網站。mysql
毫無疑問,MyBatis 和 Spring 兩大框架已經成了 Java 互聯網技術主流框架組合,它們經受住了大數據量和大批量請求的考驗,在互聯網系統中獲得了普遍的應用。使用 MyBatis-Spring 使得業務層和模型層獲得了更好的分離,與此同時,在 Spring 環境中使用 MyBatis 也更加簡單,節省了很多代碼,甚至能夠不用 SqlSessionFactory、 SqlSession 等對象,由於 MyBatis-Spring 爲咱們封裝了它們。git
摘自:《Java EE 互聯網輕量級框架整合開發》github
第一步,首先在 IDEA 中新建一個名爲【MybatisAndSpring】的 WebProject 工程:web
而後在【src】中建立 4 個空包:spring
接着新建源文件夾【config】,用於放置各類資源配置文件:sql
再在【web】文件夾下新建一個【WEB-INF】默認安全文件夾,並在其下建立一個【classes】和【lib】,並將項目的輸出位置,改在【classes】下:數據庫
工程的完整初始結構以下:apache
第二步,就是要準備項目的依賴 jar 包:緩存
在【WEB-INF】文件夾下的【lib】文件夾中放置上面列舉的 jar 包,而後添加依賴。
第三步,編寫 Spring 的配置文件:
<?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" 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"> <!-- 加載配置文件 --> <context:property-placeholder location="classpath:db.properties"/> <!-- 配置數據源 --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> <!-- sqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 加載 MyBatis 的配置文件 --> <property name="configLocation" value="mybatis/SqlMapConfig.xml"/> <!-- 數據源 --> <property name="dataSource" ref="dataSource"/> </bean> </beans>
第四步,在【mybatis】包下編寫 MyBatis 的全局配置文件 SqlMapConfig.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 --> <settings> <!-- 打開延遲加載的開關 --> <setting name="lazyLoadingEnabled" value="true"/> <!-- 將積極加載改成消極加載(即按需加載) --> <setting name="aggressiveLazyLoading" value="false"/> <!-- 打開全局緩存開關(二級緩存)默認值就是 true --> <setting name="cacheEnabled" value="true"/> </settings> <!-- 別名定義 --> <typeAliases> <package name="cn.wmyskxz.pojo"/> </typeAliases> <!-- 加載映射文件 --> <mappers> <!-- 經過 resource 方法一次加載一個映射文件 --> <mapper resource="sqlmap/UserMapper.xml"/> <!-- 批量加載mapper --> <package name="cn.wmyskxz.mapper"/> </mappers> </configuration>
在該配置文件中:
第五步,編寫 Mapper 映射文件,這裏依然定義 Mapper 映射文件的名字爲 「UserMapper.xml」 (與 SqlMapConfig.xml 中配置一致),爲了測試效果,只配置了一個查詢類 SQL 映射:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="test"> <select id="findUserById" parameterType="_int" resultType="user"> SELECT * FROM USER WHERE id = #{id} </select> </mapper>
在該配置中,輸出參數的映射爲 「user」 ,這是由於以前在 SqlMapConfig.xml 中配置了 「cn.wmyskxz.pojo」 包下的實體類使用別名(即首字母小寫的類名),因此這裏只需在 「cn.wmyskxz.pojo」 包下,建立 「finduserById」 對應的 Java 實體類 User:
package cn.wmyskxz.pojo; import java.io.Serializable; public class User implements Serializable { private int id; private String username; /* getter and setter */ }
在數據庫資源 「db.properties」 中配置了數據庫的鏈接信息,以 「key=value」 的形式配置,String 正是使用 「${}」 獲取其中 key 對應的 value 配置的:
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=UTF-8 jdbc.username=root jdbc.password=root
另外日誌配置和以前的配置同樣,我就直接黏貼了:
# Global logging configuration # 在開發環境下日誌級別要設置成 DEBUG ,生產環境設爲 INFO 或 ERROR log4j.rootLogger=DEBUG, stdout # Console output... log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
第六步,進行數據庫交互(Data Access Object)層的編寫。
因爲該項目只對 User 用戶查詢,因此 DAO 層就只有一個類,在 「cn.wmyskxz」 包下建立 DAO 層的 interface 接口,其中定義了 findUserById 方法,參數爲用戶的 id 值(int 類型):
package cn.wmyskxz.dao; import cn.wmyskxz.pojo.User; public interface UserDAO { // 根據 id 查詢用戶信息 public User findUserById(int id) throws Exception; }
而後在同一個包下建立 UserDAO 接口的實現類 UserDAOImpl:
package cn.wmyskxz.dao; import cn.wmyskxz.pojo.User; import org.apache.ibatis.session.SqlSession; import org.mybatis.spring.support.SqlSessionDaoSupport; public class UserDAOImpl extends SqlSessionDaoSupport implements UserDAO { @Override public User findUserById(int id) throws Exception { // 繼承 SqlSessionDaoSupport 類,經過 this.getSqlSession() 獲得 sqlSession SqlSession sqlSession = this.getSqlSession(); User user = sqlSession.selectOne("test.findUserById", id); return user; } }
<!-- 原始 DAO 接口 --> <bean id="userDAO" class="cn.wmyskxz.dao.UserDAOImpl"> <property name="sqlSessionFactory" ref="sqlSessionFactory"/> </bean>
在 「cn.wmyskxz.test」 包下建立【UserServiceTest】測試類:
package cn.wmyskxz.test; import cn.wmyskxz.dao.UserDAO; import cn.wmyskxz.pojo.User; import org.junit.Before; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class UserServiceTest { private ApplicationContext applicationContext; // 在執行測試方法以前首先獲取 Spring 配置文件對象 // 註解@Before在執行本類全部測試方法以前先調用這個方法 @Before public void setup() throws Exception { applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml"); } @Test public void testFindUserById() throws Exception { // 經過配置資源對象獲取 userDAO 對象 UserDAO userDAO = (UserDAO) applicationContext.getBean("userDAO"); // 調用 UserDAO 的方法 User user = userDAO.findUserById(1); // 輸出用戶信息 System.out.println(user.getId() + ":" + user.getUsername()); } }
運行測試方法,輸出結果以下:
上面的實例程序並無使用 Mapper 動態代理和註解來完成,下面咱們就來試試如何用動態代理和註解:
在【mapper】下新建一個【UserQueryMapper】代理接口,並使用註解:
package cn.wmyskxz.mapper; import cn.wmyskxz.pojo.User; import org.apache.ibatis.annotations.Select; public interface UserQueryMapper { @Select("SELECT * FROM USER WHERE id = #{id}") public User findUserById(int id) throws Exception; }
如今有了代理類,咱們須要通知 Spring 在這裏來掃描到該類,Mapper 掃描配置對象須要用專門的掃描器:
<!-- Mapper 掃描器 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 掃描 cn.wmyskxz.mapper 包下的組件 --> <property name="basePackage" value="cn.wmyskxz.mapper"/> </bean>
這一次咱們獲取的再也不是 userDAO 對象,而是定義的 Mapper 代理對象 userQueryMapper:
package cn.wmyskxz.test; import cn.wmyskxz.mapper.UserQueryMapper; import cn.wmyskxz.pojo.User; import org.junit.Before; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class UserServiceTest { private ApplicationContext applicationContext; // 在執行測試方法以前首先獲取 Spring 配置文件對象 // 註解@Before在執行本類全部測試方法以前先調用這個方法 @Before public void setup() throws Exception { applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml"); } @Test public void testFindUserById() throws Exception { // 經過配置資源對象獲取 userDAO 對象 UserQueryMapper userQueryMapper = (UserQueryMapper) applicationContext.getBean("userQueryMapper"); // 調用 UserDAO 的方法 User user = userQueryMapper.findUserById(1); // 輸出用戶信息 System.out.println(user.getId() + ":" + user.getUsername()); } }
運行測試方法,獲得正確結果:
能夠看到,查詢結果和以前非 Mapper 代理的查詢結果同樣。
歡迎轉載,轉載請註明出處!
簡書ID:@我沒有三顆心臟
github:wmyskxz 歡迎關注公衆微信號:wmyskxz_javaweb 分享本身的Java Web學習之路以及各類Java學習資料