1. Spring和各個框架的整合
Spring目前是JavaWeb開發中最終的框架,提供一站式服務,可以其他各個框架整合集成
Spring整合方案
1.1. SSH
ssh是早期的一種整合方案
Struts2 : Web層框架
Spring : 容器框架
Hibernate : 持久層框架
1.2. SSM
主流的項目架構的三大框架(相對其他框架而言,最優秀)
SpringMVC : spring自己家的 Web層框架,spring的一個模塊
Spring :容器框架
MyBatis :持久層框架
2. Spring與MyBatis整合
2.1. 集成思路
實際開發,使用Maven項目,直接引入項項目在Maven倉庫中的坐標即可
學習階段: 手動導入jar包,從零開始集成(鞏固基礎知識)
2.2. 創建java項目
准備集成相關jar包
完成項目層與層之間spring對象的創建和依賴關系的維護
package cn.sxt.pojo; public class User { private Integer id; private String name; private String password; private Integer age; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "User [id=" + id + ", name=" + name + ", password=" + password + ", age=" + age + "]"; } public User(Integer id, String name, String password, Integer age) { super(); this.id = id; this.name = name; this.password = password; this.age = age; } public User() { super(); // TODO Auto-generated constructor stub } }
package cn.sxt.mapper; import java.util.List; import cn.sxt.pojo.User; public interface UserMapper { int insert(User user); int deleteByPrimaryKey(Integer id); int updateByPrimaryKey(User user); User selectByPrimaryKey(Integer id); List<User> selectList(); }
<?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="cn.sxt.mapper.UserMapper"> <insert id="insert" parameterType="User" keyColumn="id" keyProperty="id" useGeneratedKeys="true" > insert into user (name,password,age)values(#{name},#{password},#{age}) </insert> <!-- 單行查詢 <select resultType =""> 查詢功能的標簽 resultType : 返回結果的數據類型,和接口對應方法的返回類型必須一致 --> <select id="selectByPrimaryKey" parameterType="Integer" resultType="User"> <!-- #{對象屬性} ,主鍵理論上任何值都可以 #{abc},#{xxx},可以不用對象屬性--> select * from user where id = #{id} </select> <!-- 多行查詢 無論單行或者多行查詢,返回的數據類型都是 對應 pojo 對應的對象類型 --> <select id="selectList" resultType="User"> select * from user </select> <!-- 刪除操作 --> <delete id="deleteByPrimaryKey" parameterType="Integer"> delete from user where id = #{id} </delete> <!-- 修改操作 --> <update id="updateByPrimaryKey" parameterType="User"> <!-- 固定語義的sql語句 --> update user set name = #{name},password = #{password},age = #{age} where id = #{id} </update> </mapper>
package cn.sxt.service; import java.util.List; import cn.sxt.pojo.User; public interface UserService { int insert(User user); int deleteByPrimaryKey(Integer id); int updateByPrimaryKey(User user); User selectByPrimaryKey(Integer id); List<User> selectList(); }
package cn.sxt.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import cn.sxt.mapper.UserMapper; import cn.sxt.pojo.User; import cn.sxt.service.UserService; @Service public class UserServiceImpl implements UserService { /* * 問題1 : UserMapper是接口,如何創建對象? * 答: 使用MyBatis的SqlSession 會話對象。 * * 問題2:SqlSession如何創建? * 答: 使用MyBatis的SqlSessionFactory 工廠對象創建 * * 問題3:SqlSessionFactory工廠對象如何創建? * * 答:在使用Spring之前 * 開發者自己寫代碼讀取MyBatis配置文件,創建SqlSessionFactory * 使用Spring之后,讓Spring框架幫我們創建 * * 問題4:SqlSessionFactory 工廠對象Spring框架如何創建出來? * * 答:MyBatis工廠對象創建的類在 MyBatis框架和Spring集成的橋梁包mybatis-spring-1.3.1.jar * 的org.mybatis.spring.SqlSessionFactoryBean 負責創建工廠對象 * 開發者只需要在Spring配置配置此類就可以創建出來SqlSessionFactory對象 * */ @Autowired private UserMapper mapper; @Override public int insert(User user) { return mapper.insert(user); } @Override public int deleteByPrimaryKey(Integer id) { return mapper.deleteByPrimaryKey(id); } @Override public int updateByPrimaryKey(User user) { return mapper.updateByPrimaryKey(user); } @Override public User selectByPrimaryKey(Integer id) { return mapper.selectByPrimaryKey(id); } @Override public List<User> selectList() { return mapper.selectList(); } }
package cn.sxt.test; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import cn.sxt.pojo.User; import cn.sxt.service.UserService; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext.xml") public class test01 { @Autowired private UserService service; @Test public void testInsert() { User user = new User(null, "虛竹", "xuzhu", 30); service.insert(user); } @Test public void testDeleteByPrimaryKey() { service.deleteByPrimaryKey(10); } @Test public void testUpdateByPrimaryKey() { User user = new User(9, "孫悟空", "wukong", 600); service.updateByPrimaryKey(user ); } @Test public void testSelectByPrimaryKey() { User user = service.selectByPrimaryKey(11); } @Test public void testSelectList() { List<User> users = service.selectList(); } }
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" 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 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd "> <!-- 配置組件包掃描的位置 --> <context:component-scan base-package="cn.sxt" /> <!-- 讀取db.properties配置文件到Spring容器中 --> <context:property-placeholder location="classpath:db.properties" /> <!-- 配置 阿里巴巴的 druid 數據源(連接池) --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <!-- SpringEL 語法 ${key} --> <property name="driverClassName" value="${jdbc.driverClassName}" /> <property name="url" value="${jdbc.url}" /> <!-- ${username}如果key是username,name 默認spring框架調用的當前操作系統的賬號 解決方案:可以統一給key加一個前綴 --> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <property name="maxActive" value="${jdbc.maxActive}" /> </bean> <!-- 創建SqlSessionFactory MyBatis會話工廠對象 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 注入數據源 --> <property name="dataSource" ref="dataSource" /> <!-- 讀取映射文件 ,MyBatis的純注解不用配置 --> <property name="mapperLocations"> <array> <!-- 配置單個映射文件 --> <!-- <value>classpath:cn/zj/ssm/mapper/UserMapper.xml</value> --> <!-- 配置多個映射文件使用 * 通配符 --> <value>classpath:cn/sxt/mapper/*Mapper.xml</value> </array> </property> <!-- 配置mybatis-confg.xml主配置文件(注配置文件可以保留一些個性化配置,緩存,日志,插件) --> <property name="configLocation" value="classpath:mybatis-config.xml" /> <!-- 配置別名,使用包掃描 --> <property name="typeAliasesPackage" value="cn.sxt.pojo"></property> </bean> <!-- SqlSession 不用單獨創建,每次做crud操作都需要Mapper接口的代理對象 而代理對象的創建又必須有 SqlSession對象創建 Spring在通過MyBatis創建 Mapper接口代理對象的時候,底層自動把SqlSession會話對象創建出來 --> <!-- 創建UserMapper接口的代理對象,創建單個代理對象 參考橋梁包:org.mybatis.spring.mapper.MapperFactoryBean<T> 此類就是創建 Mapper 代理對象的類 --> <!--<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> 注入UserMapper接口 <property name="mapperInterface" value="cn.sxt.mapper.UserMapper"/> 注入sqlSessionFactory工廠對象 <property name="sqlSessionFactory" ref="sqlSessionFactory"/> </bean> --> <!-- 使用包掃描創建代理對象,包下面所有Mapper接口統一創建代理對象 使用橋梁包下面 : org.mybatis.spring.mapper.MapperScannerConfigurer 可以包掃描創建所有映射接口的代理對象 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 配置SqlSessionFactoryBean的名稱 --> <property name="basePackage" value="cn.sxt.mapper"/> <!-- 可選,如果不寫,Spring啟動時候。容器中。自動會按照類型去把SqlSessionFactory對象注入進來 --> <!-- <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> --> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> </bean> <!-- 1.配置事務管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!-- 注入數據源 --> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 2.配置事務的細節 配置事務通知/增強 --> <tx:advice id="tx" transaction-manager="transactionManager" > <!-- 配置屬性 --> <tx:attributes> <!-- DQL --> <tx:method name="select*" read-only="true" isolation="REPEATABLE_READ" propagation="REQUIRED" timeout="5"/> <tx:method name="query*" read-only="true" isolation="REPEATABLE_READ" propagation="REQUIRED" timeout="5"/> <tx:method name="get*" read-only="true" isolation="REPEATABLE_READ" propagation="REQUIRED" timeout="5"/> <tx:method name="find*" read-only="true" isolation="REPEATABLE_READ" propagation="REQUIRED" timeout="5"/> <!-- 其他 --> <tx:method name="*" read-only="false" isolation="REPEATABLE_READ" propagation="REQUIRED" timeout="5"/> </tx:attributes> </tx:advice> <!-- 3.使用AOP將事務切到Service層 --> <aop:config> <!-- 配置切入點 --> <aop:pointcut expression="execution(* cn.zj.ssm.service..*.*(..))" id="pt"/> <!-- 配置切面= 切入點+通知 --> <aop:advisor advice-ref="tx" pointcut-ref="pt"/> </aop:config> </beans>
jdbc.driverClassName=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT jdbc.username=root jdbc.password=gzsxt jdbc.maxActive=10
# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.cn.sxt.mapper=TRACE
# 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
<?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> <!-- mybatis框架的個性化配置可在此配置 --> </configuration>