首先建立一個對象 package com.itmayiedu.entity; public class UserEntity { private String name; private Integer age; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
建立spring的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" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" 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/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- 根據id userentity <bean id="userEntity" class="com.itmayiedu.entity.UserEntity" /> </beans>
##根據spring建立文件 package com.itmayiedu.entity.controller; import com.itmayiedu.entity.UserEntity; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainTest { public static void main(String[] args) { ClassPathXmlApplicationContext application = new ClassPathXmlApplicationContext("spring.xml"); UserEntity userEntity = (UserEntity) application.getBean("userEntity"); System.out.println(userEntity); } }
首先如何證實spring單例的css
package com.itmayiedu.entity; public class UserEntity { private String name; private Integer age; public UserEntity() { System.out.println("我建立了一個對象"); } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
## 若是地址相同則證實是同一個對象,spring是單例的,
package com.itmayiedu.entity.controller; import com.itmayiedu.entity.UserEntity; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainTest { public static void main(String[] args) { ClassPathXmlApplicationContext application = new ClassPathXmlApplicationContext("spring.xml"); UserEntity userEntity = (UserEntity) application.getBean("userEntity"); UserEntity userEntity1 = (UserEntity) application.getBean("userEntity"); System.out.println(userEntity==userEntity1); System.out.println(userEntity); }
## 輸出結果:true }
<!-- prototype -->
<bean id="userEntity" class="com.itmayiedu.entity.UserEntity" scope="prototype"/>
構造函數html
工廠建立對象前端
工廠類 靜態工廠java
工廠內 非靜態工廠mysql
想說一個根據構造函數來建立對象jquery
無參函數剛剛已經說過那,這裏主要說一下有參函數,在實體類中咱們須要給給他聲明一個有參函數git
<!-- 無參構造函數 --> <bean id="user1" class="com.itmayiedu.entity.UserEntity" scope="prototype" /> <!-- 有參構造函數 --> <bean id="user2" class="com.itmayiedu.entity.UserEntity"> <constructor-arg name="name" type="java.lang.String" value="張三"></constructor-arg> <constructor-arg name="age" type="java.lang.Integer" value="18"></constructor-arg> </bean>
這裏能夠看到無參構造函數的優先於午參構造函數的github
首先咱們建立一個工廠類web
package com.itmayiedu.entity; import javax.swing.text.html.parser.Entity; public class ObjectFactory { public UserEntity getInstance(){ System.out.println(); return new UserEntity("wwww",23); } public static UserEntity getStaticInstance(){ System.out.println(); return new UserEntity("ggg",66); } }
<?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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" 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/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- 無參構造函數 --> <bean id="user1" class="com.itmayiedu.entity.UserEntity" scope="prototype" /> <!-- 有參構造函數 --> <bean id="user2" class="com.itmayiedu.entity.UserEntity"> <constructor-arg name="name" type="java.lang.String" value="張三"></constructor-arg> <constructor-arg name="age" type="java.lang.Integer" value="18"></constructor-arg> </bean> <bean id="factory" class="com.itmayiedu.entity.ObjectFactory"></bean> <!-- 經過實例工廠方法建立 --> <bean id="user3" factory-bean="factory" factory-method="getInstance"></bean> <!-- 經過靜態工廠方法建立 --> <bean id="user4" class="com.itmayiedu.entity.ObjectFactory" factory-method="getStaticInstance"></bean> </beans>
注入的方式面試
經過構造函數(上面已經演示過)
經過set方法給對象賦值
p名稱空間
自動裝配
註解
在這裏講解set方法的注入
### 曾經迪士尼面試官問過一道題,在spring中加入A依賴B 如何進行注入, 當時特別簡單的一道題,結果想歪啦.說什麼A的實體類有一個B對象進行new,接下來進行正解
這樣的話,就完成了抵賴注入.
那麼不少人很好奇問啦.爲何叫setter注入.沒setter爲何就不行了.其實他底層用了反射setter方法修改屬性辦法,詳情能夠看個人過去的博客
https://www.cnblogs.com/itcastwzp/p/10971746.html
P標籤注入
<bean id="userService" class="cn.itmayiedu.UserAction" p:userService-ref="userDao"></bean>
這種方式恨簡單.可是用的人不多,做爲了解就好
若是想使用spring的註解,咱們須要在xml中開啓註解的權限而且掃描注的範圍
<context:component-scan base-package="com.cloudwalk"></context:component-scan>
@Respsitory 他的做用 相似 用於數據層
@Sevice 服務層
@Controller 控制層
做用相似
<bean id="factory" class="com.itmayiedu.entity.ObjectFactory"></bean>
@Autowired相似
<property name="userDao" ref="userDao"></property>
aop能夠相似看重複的代碼當作切面而後直接引用
首先xml開啓aop
<!--開啓AOP註解--> <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
@Component @Aspect public class Aop {
/** 執行方法執行前**/ @Before("execution(* com.itmayiedu.entity.controller.UserService.add(..))") public void begin(){ System.out.println("開啓事務"); }
/**執行方法執行後**/ @After("execution(* com.itmayiedu.entity.controller.UserService.add(..))") public void commit(){ System.out.println("事務提交"); } /**執行方法拋異常**/ @AfterThrowing("execution(* com.itmayiedu.entity.controller.UserService.add(..))") public void error(){ System.out.println("啊,我有異常啦"); } /**方法運行結束後**/ @AfterReturning("execution(* com.itmayiedu.entity.controller.UserService.add(..))") public void run(){ System.out.println("運行"); } }
而後直接調用便可
這裏難點和重點須要學習的是spring aop的表達式的寫法 也就是這寫aop執行在那些地方有效
具體參考http://www.javashuo.com/article/p-mkucndzl-hw.html這位大佬的博客
首先取消@aspect註解
配置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" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" 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/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <context:component-scan base-package="com.itmayiedu"></context:component-scan> <!-- 把切面類注入到容器中--> <bean id="aop" class="com.itmayiedu.entity.controller.Aop"> </bean> <aop:config> <!-- 書寫spring aop 攔截表達式--> <aop:pointcut id="pf" expression="execution(* com.itmayiedu.entity.controller.UserService.add(..))"></aop:pointcut> <!-- 標記一個且表--> <aop:aspect ref="aop"> <!-- 用什麼通知,通知用哪一個攔截表達式--> <aop:before method="begin" pointcut-ref="pf"></aop:before> <aop:after method="commit" pointcut-ref="pf"></aop:after> </aop:aspect> </aop:config> </beans>
運行結果
網上關於相似的理論問題一大推: 這裏推薦這個博客,簡單易懂.網上大部分寫的都太專業抽象啦
https://baijiahao.baidu.com/s?id=1611918898724887602&wfr=spider&for=pc
事務案例
如今摸一個簡單的CRUD(增刪改查)闡述事務
pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.bwie</groupId> <artifactId>spring</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <!-- 引入Spring-AOP等相關Jar --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>3.0.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>3.0.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>3.0.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>3.0.6.RELEASE</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>1.6.1</version> </dependency> <dependency> <groupId>aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.5.3</version> </dependency> <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>2.1_2</version> </dependency> <!-- https://mvnrepository.com/artifact/com.mchange/c3p0 --> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.5.2</version> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.37</version> </dependency> </dependencies> </project>
<?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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 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/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 開啓註解 --> <context:component-scan base-package="com.itmayiedu"></context:component-scan> <!-- 1. 數據源對象: C3P0鏈接池 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"></property> <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/ibis"></property> <property name="user" value="root"></property> <property name="password" value="root"></property> </bean> <!-- 2. JdbcTemplate工具類實例 --> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"></property> </bean> </beans>
實體類
package com.itmayiedu.entity; public class UserEntity { private String name; private Integer age; /** * 若是是單例一次運行 是輸出 第二次不會輸出 */ public UserEntity() { System.out.println("我建立了一個對象"); } public UserEntity(String name, Integer age) { System.out.println("有償構造函數"); this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "UserEntity{" + "name='" + name + '\'' + ", age=" + age + '}'; } }
dao
package com.itmayiedu.dao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; @Repository public class UserDao { @Autowired private JdbcTemplate jdbcTemplate; public void add(String name, Integer age) { String sql = "INSERT INTO t_user(uname, usalary) VALUES(?,?);"; int update = jdbcTemplate.update(sql, name, age); System.out.println("updateResult:" + update); } }
service
package com.itmayiedu.service; import com.itmayiedu.dao.UserDao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class UserService { @Autowired private UserDao userDao; public void add() { userDao.add("lisi", 18); int i=1/0;//可能會發生異常 userDao.add("yushengjun", 19); } }
controller
package com.itmayiedu.controller; import com.itmayiedu.service.UserService; import org.springframework.context.support.ClassPathXmlApplicationContext; public class UserController { public static void main(String[] args) { ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml"); UserService userService = (UserService) applicationContext.getBean("userService"); userService.add(); } }
當運行1/0運行的時候能夠發現數據庫默認只添加了第一個數據然後面的數據沒有添加 這是不容許
能夠當成 轉帳 我這裏只扣錢啦, 對象增長錢的操做沒有執行
那麼如何操做事務呢
事務的開啓能夠分爲
編程式事務: 代碼中開啓
編程式事務控制 本身手動控制事務,就叫作編程式事務控制。 Jdbc代碼: Conn.setAutoCommite(false); // 設置手動控制事務 Hibernate代碼: Session.beginTransaction(); // 開啓一個事務 【細粒度的事務控制: 能夠對指定的方法、指定的方法的某幾行添加事務控制】 (比較靈活,但開發起來比較繁瑣: 每次都要開啓、提交、回滾.)
聲明式事務控制
Spring提供了對事務的管理, 這個就叫聲明式事務管理。
Spring提供了對事務控制的實現。用戶若是想用Spring的聲明式事務管理,只須要在配置文件中配置便可; 不想使用時直接移除配置。這個實現了對事務控制的最大程度的解耦。
Spring聲明式事務管理,核心實現就是基於Aop。
【粗粒度的事務控制: 只能給整個方法應用事務,不能夠對方法的某幾行應用事務。】
(由於aop攔截的是方法。)
Spring聲明式事務管理器類:
Jdbc技術:DataSourceTransactionManager
Hibernate技術:HibernateTransactionManager
主要說
DataSourceTransactionManager
先聲明一個事務管理類
package com.itmayiedu.Transaction; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.stereotype.Component; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.DefaultTransactionDefinition; @Component public class TransactionUtils { // 事物管理器 @Autowired private DataSourceTransactionManager dataSourceTransactionManager; /** * * @return 返回事務的狀態 */ public TransactionStatus begin() { TransactionStatus transaction = dataSourceTransactionManager.getTransaction(new DefaultTransactionDefinition()); return transaction; } /** * 提交 * @param transaction */ public void commit(TransactionStatus transaction) { dataSourceTransactionManager.commit(transaction); } /** * 回滾 * @param transaction */ public void rollback(TransactionStatus transaction) { dataSourceTransactionManager.rollback(transaction); } }
在service中添加事務的管理
package com.itmayiedu.service; import com.itmayiedu.Transaction.TransactionUtils; import com.itmayiedu.dao.UserDao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.annotation.TransactionManagementConfigurationSelector; import sun.instrument.TransformerManager; @Service public class UserService { @Autowired private UserDao userDao; @Autowired private TransactionUtils transactionUtils; TransactionStatus begin = null; public void add() { try { begin = transactionUtils.begin(); userDao.add("lisi", 18); int i=1/0;//可能會發生異常 userDao.add("yushengjun", 19); transactionUtils.commit(begin); } catch (Exception e){ //發生回滾 transactionUtils.rollback(begin); } } }
從下圖能夠看出雖然前面已經執行了一條SQL語句成功,可是由於報錯,由於rollback 致使數據沒有插入到數據庫
聲明式 --- 工做中經常使用 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" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 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/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 開啓註解 --> <context:component-scan base-package="com.itmayiedu"></context:component-scan> <!-- 1. 數據源對象: C3P0鏈接池 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"></property> <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/ibis"></property> <property name="user" value="root"></property> <property name="password" value="root"></property> </bean> <!-- 2. JdbcTemplate工具類實例 --> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"></property> </bean> <bean id="DataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!--配置事物加強--> <tx:advice id="txAdvice" transaction-manager="DataSourceTransactionManager"> <tx:attributes> <tx:method name="get*" read-only="true" /> <tx:method name="find*" read-only="true" /> <tx:method name="*" read-only="false" /> </tx:attributes> </tx:advice> <!-- Aop配置: 攔截哪些方法(切入點表表達式) + 應用上面的事務加強配置 --> <aop:config> <aop:pointcut expression="execution(* com.itmayiedu.service.*.*(..))" id="pt" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="pt" /> </aop:config> </beans>
在代碼定義這些代碼便可是使用,其中
<tx:method name="get*" read-only="true" /> 指的是查詢不涉及事物的問題,只進行只讀操做,其他寫的操做統一開始事物
<aop:pointcut>爲AOP事物的切面
運行結果
能夠看到執行的結果還有回一個數據的
主要是由於沒有進行回滾,咱們須在cath添加當有異常時,進行回滾的操做
事物是程序運行若是沒有錯誤,會自動提交事物,若是程序運行發生異常,則會自動回滾。
若是使用了try捕獲異常時.必定要在catch裏面手動回滾。
事物手動回滾代碼
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
package com.itmayiedu.service; import com.itmayiedu.Transaction.TransactionUtils; import com.itmayiedu.dao.UserDao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.annotation.TransactionManagementConfigurationSelector; import org.springframework.transaction.interceptor.TransactionAspectSupport; import sun.instrument.TransformerManager; @Service public class UserService { @Autowired private UserDao userDao; @Autowired private TransactionUtils transactionUtils; TransactionStatus begin = null; public void add() { try { userDao.add("lisi", 18); int i=1/0;//可能會發生異常 System.out.println("2222"); userDao.add("yushengjun", 19); } catch (Exception e) { TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } } }
能夠看到代碼雖然執行那,可是數據庫沒有數據,說明數據被回滾啦;
接下來說解下你們最愛的註解方式
<?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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 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/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 開啓註解 --> <context:component-scan base-package="com.itmayiedu"></context:component-scan> <!-- 1. 數據源對象: C3P0鏈接池 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"></property> <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/ibis"></property> <property name="user" value="root"></property> <property name="password" value="root"></property> </bean> <!-- 2. JdbcTemplate工具類實例 --> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"></property> </bean> <bean id="DataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!--開啓事物註解--> <tx:annotation-driven transaction-manager="DataSourceTransactionManager"></tx:annotation-driven> <!--配置事物加強 <tx:advice id="txAdvice" transaction-manager="DataSourceTransactionManager"> <tx:attributes> <tx:method name="get*" read-only="true" /> <tx:method name="find*" read-only="true" /> <tx:method name="*" read-only="false" /> </tx:attributes> </tx:advice>--> <!-- Aop配置: 攔截哪些方法(切入點表表達式) + 應用上面的事務加強配置 <aop:config> <aop:pointcut expression="execution(* com.itmayiedu.service.*.*(..))" id="pt" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="pt" /> </aop:config> --> </beans>
package com.itmayiedu.service; import com.itmayiedu.Transaction.TransactionUtils; import com.itmayiedu.dao.UserDao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.annotation.TransactionManagementConfigurationSelector; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.interceptor.TransactionAspectSupport; import sun.instrument.TransformerManager; @Service public class UserService { @Autowired private UserDao userDao; @Transactional public void add() { userDao.add("lisi", 18); int i=1/0;//可能會發生異常 System.out.println("2222"); userDao.add("yushengjun", 19); } }
便可完成
事務的傳播行爲--- 之前面試官考過,當時感受沒啥用,就沒背,但是那時候面試官居然還問啦。。。今天特地總結下
舉一個最多見的例子
好比 在我添加的時候,我添加的方法裏面調用了一個添加日子的記錄
然而若是使用@Transactional註解的發,由於異常致使所有信息回滾,而日誌回滾不是咱們所但願的,咱們但願無論又沒出出現異常,咱們都須要進行記錄,而不是回滾
此時就須要咱們的事物的傳播行爲
package com.itmayiedu.dao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; @Repository public class UserDao { @Autowired private JdbcTemplate jdbcTemplate; public void add(String name, Integer age) { String sql = "INSERT INTO t_user(uname, usalary) VALUES(?,?);"; int update = jdbcTemplate.update(sql, name, age); System.out.println("updateResult:" + update); } }
package com.itmayiedu.service; import com.itmayiedu.Transaction.TransactionUtils; import com.itmayiedu.dao.UserDao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.annotation.TransactionManagementConfigurationSelector; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.interceptor.TransactionAspectSupport; import sun.instrument.TransformerManager; @Service public class UserService { @Autowired private UserDao userDao; @Autowired private LogDao logDao; @Transactional public void add() { logDao.addLog("我在記錄", 1); userDao.add("yushengjun", 19); int i = 1 / 0; } }
1 能夠看到 add 方法使用 2 3 @Transactional修飾的,而後add方法中還調用了一個 4 @Transactional的修飾的addlog()方法 5 此時當使用@Transactional的時候,默認採起的是REQUIRED的隔離級別 6 7 8 PROPAGATION_REQUIRED--支持當前事務,若是當前沒有事務,就新建一個事務。這是最多見的選擇。 9 PROPAGATION_SUPPORTS--支持當前事務,若是當前沒有事務,就以非事務方式執行。 10 PROPAGATION_MANDATORY--支持當前事務,若是當前沒有事務,就拋出異常。 11 PROPAGATION_REQUIRES_NEW--新建事務,若是當前存在事務,把當前事務掛起。 12 PROPAGATION_NOT_SUPPORTED--以非事務方式執行操做,若是當前存在事務,就把當前事務掛起。 13 PROPAGATION_NEVER--以非事務方式執行,若是當前存在事務,則拋出異常。
在這裏的是一個難點: 我舉一個例子,假如我去飯店陪客戶吃飯,看見同窗都在一桌吃飯,我此時有兩種選擇,一種是陪他吃飯但沒法和客戶溝通,完成不了本身的功能,
另外一種就是我另外一桌,本身單獨完成的本身的功能,無論他們.. 這裏的一桌,就是開了一個不一樣於同窗那一餐桌的事物
若是先知足由於異常致使所有信息回滾,而日誌回滾不是咱們所但願的,咱們但願無論又沒出出現異常,咱們都須要進行記錄,而不是回滾的需求
只須要更改事物的傳播屬性就好就好
輸出結果
能夠看到 日子有了記錄 和 人員表沒有 .. 亂碼不要管..這個客戶端我也是第一次用..不知道用哪一個UTF-8的編碼...
下面爲spring項目訓練
SSM整合+視頻網站開發
使用SpringMVC+Mybatis+Spring+Maven進行分模塊整合 簡單實現視頻網站開發
視頻網站構建模式
分爲:自建模式和第三方模式
自建模式:須要本身搭建服務器、解決CDN加速問題、提升SDK、防盜鏈等問題
第三方模式:使用第三方雲視頻接口、阿里雲、保利雲(8毛)、樂視雲(4毛G)。
講述一下 螞蟻課堂網站視頻架構
後端:SpringMVC、Spring、Mybatis
前端:jquery
itmayiedu-parent |
---父類工程 |
itmayiedu-commons |
---工具類 |
itmayiedu-entity |
---實體類 |
itmayiedu-dao |
---數據庫訪問層 |
itmayiedu-service |
---服務層 |
itmayiedu-web |
---web層 |
<!-- 集中定義依賴版本號 --> <properties> <junit.version>4.12</junit.version> <spring.version>4.1.3.RELEASE</spring.version> <mybatis.version>3.2.8</mybatis.version> <mybatis.spring.version>1.2.2</mybatis.spring.version> <mybatis.paginator.version>1.2.15</mybatis.paginator.version> <mysql.version>5.1.32</mysql.version> <slf4j.version>1.6.4</slf4j.version> <jackson.version>2.4.2</jackson.version> <druid.version>1.0.9</druid.version> <httpclient.version>4.3.5</httpclient.version> <jstl.version>1.2</jstl.version> <servlet-api.version>2.5</servlet-api.version> <jsp-api.version>2.0</jsp-api.version> <joda-time.version>2.5</joda-time.version> <commons-lang3.version>3.3.2</commons-lang3.version> <commons-io.version>1.3.2</commons-io.version> <commons-net.version>3.3</commons-net.version> <pagehelper.version>5.0.0</pagehelper.version> <jsqlparser.version>0.9.1</jsqlparser.version> <commons-fileupload.version>1.3.1</commons-fileupload.version> <jedis.version>2.7.2</jedis.version> <solrj.version>4.10.3</solrj.version> </properties> <dependencyManagement> <dependencies> <!-- 時間操做組件 --> <dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifactId> <version>${joda-time.version}</version> </dependency> <!-- Apache工具組件 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>${commons-lang3.version}</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-io</artifactId> <version>${commons-io.version}</version> </dependency> <dependency> <groupId>commons-net</groupId> <artifactId>commons-net</artifactId> <version>${commons-net.version}</version> </dependency> <!-- Jackson Json處理工具包 --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.version}</version> </dependency> <!-- httpclient --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>${httpclient.version}</version> </dependency> <!-- 單元測試 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <!-- 日誌處理 --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <!-- Mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>${mybatis.spring.version}</version> </dependency> <dependency> <groupId>com.github.miemiedev</groupId> <artifactId>mybatis-paginator</artifactId> <version>${mybatis.paginator.version}</version> </dependency> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>${pagehelper.version}</version> </dependency> <!-- MySql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <!-- 鏈接池 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>${druid.version}</version> </dependency> <!-- Spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>${spring.version}</version> </dependency> <!-- JSP相關 --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>${jstl.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>${servlet-api.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jsp-api</artifactId> <version>${jsp-api.version}</version> <scope>provided</scope> </dependency> <!-- 文件上傳組件 --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>${commons-fileupload.version}</version> </dependency> <!-- Redis客戶端 --> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>${jedis.version}</version> </dependency> </dependencies> </dependencyManagement>
<build> <finalName>${project.artifactId}</finalName> <plugins> <!-- 資源文件拷貝插件 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> <version>2.7</version> <configuration> <encoding>UTF-8</encoding> </configuration> </plugin> <!-- java編譯插件 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.2</version> <configuration> <source>1.8</source> <target>1.8</target> <encoding>UTF-8</encoding> </configuration> </plugin> </plugins> <pluginManagement> <plugins> <!-- 配置Tomcat插件 --> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> </plugin> </plugins> </pluginManagement> </build> |
<dependencies> <!-- JSP相關 --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jsp-api</artifactId> <scope>provided</scope> </dependency> <!-- 文件上傳組件 --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> </dependency> <!-- springwebmvc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> </dependency> <dependency> <groupId>com.itmayiedu</groupId> <artifactId>itmayiedu-entity</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.5.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.5.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.jr</groupId> <artifactId>jackson-jr-all</artifactId> <version>2.5.0</version> </dependency> </dependencies> |
<?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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- springmvc 掃包範圍 --> <context:component-scan base-package="com.itmayiedu.controller" /> <!-- 開啓springmvc註解 --> <mvc:annotation-driven /> <!-- 視圖跳轉類型 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> </beans>
|
<!-- 解決post亂碼 --> <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <!-- <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> --> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- springmvc的前端控制器 --> <servlet> <servlet-name>itmayiedu-web</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- contextConfigLocation不是必須的,若是不配置contextConfigLocation, springmvc的配置文件默認在:WEB-INF/servlet的name+"-servlet.xml" --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>itmayiedu-web</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> |
@Controller publicclass TestController { privatestaticfinal String TEST="test"; @RequestMapping("/test") public String test(){ returnTEST; } } |
Ok springMVC環境搭建成功
--視頻類型表 CREATE TABLE `video_type` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主鍵(自增加)', `type_name` varchar(30) DEFAULT NULL COMMENT '視頻類型', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8; --視頻詳情表 CREATE TABLE `video_info` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主鍵(自增加)', `video_name` varchar(150) DEFAULT NULL COMMENT '視頻名稱', `video_url` varchar(100) DEFAULT NULL COMMENT '封面圖片', `video_html` varchar(500) DEFAULT NULL COMMENT '視頻html執行元素', `video_type_id` int DEFAULT NULL COMMENT '關聯typeID', `video_del` INT DEFAULT 0 COMMENT '是否顯示 0顯示 1隱藏', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
|
<!-- 依賴管理 --> <dependencies> <dependency> <groupId>com.itmayiedu</groupId> <artifactId>weixin-entity</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> <!-- Mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> </dependency> <dependency> <groupId>com.github.miemiedev</groupId> <artifactId>mybatis-paginator</artifactId> </dependency> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> </dependency> <!-- MySql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!-- 鏈接池 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> </dependency> </dependencies> <!-- 若是不添加此節點mybatis的mapper.xml文件都會被漏掉。 --> <build> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources> </build> |
<dependencies> <dependency> <groupId>com.itmayiedu</groupId> <artifactId>itmayiedu-dao</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> <!-- Spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> </dependency> <!-- 日誌處理 --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> </dependency> </dependencies> |
jdbc.driver=com.mysql.jdbc.Driver jdbc.host=localhost jdbc.database=test jdbc.userName=root jdbc.passWord=root jdbc.initialSize=0 jdbc.maxActive=20 jdbc.maxIdle=20 jdbc.minIdle=1 jdbc.maxWait=1000
|
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 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-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd"> <!-- 開啓註解 --> <context:component-scan base-package="com.itmayiedu.service"></context:component-scan> </beans>
|
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 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-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!-- 數據庫鏈接池 --> <!-- 加載配置文件 --> <context:property-placeholder location="classpath:properties/*.properties" /> <!-- 數據庫鏈接池 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driver}" /> <property name="url" value="jdbc:mysql://${jdbc.host}:3306/${jdbc.database}?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull" /> <property name="username" value="${jdbc.userName}" /> <property name="password" value="${jdbc.passWord}" /> <!-- 初始化鏈接大小 --> <property name="initialSize" value="${jdbc.initialSize}"></property> <!-- 鏈接池最大數量 --> <property name="maxActive" value="${jdbc.maxActive}"></property> <!-- 鏈接池最大空閒 --> <property name="maxIdle" value="${jdbc.maxIdle}"></property> <!-- 鏈接池最小空閒 --> <property name="minIdle" value="${jdbc.minIdle}"></property> </bean>
<!-- spring和MyBatis完美整合,不須要mybatis的配置映射文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自動掃描mapping.xml文件 --> <property name="mapperLocations" value="classpath:mappings/*.xml"></property> </bean>
<!-- DAO接口所在包名,Spring會自動查找其下的類 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.itmayiedu.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean>
<!-- (事務管理)transaction manager, use JtaTransactionManager for global tx --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> </beans> |
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 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-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd"> <!-- 事務管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!-- 數據源 --> <property name="dataSource" ref="dataSource" /> </bean> <!-- 通知 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <!-- 傳播行爲 --> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="create*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="find*" propagation="SUPPORTS" read-only="true" /> <tx:method name="select*" propagation="SUPPORTS" read-only="true" /> <tx:method name="get*" propagation="SUPPORTS" read-only="true" /> </tx:attributes> </tx:advice> <!-- 切面 --> <aop:config> <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.itmayiedu.service.*.*(..))" /> </aop:config> </beans>
|
/** * * @classDesc: 功能描述:(測試TestController) * @author: 餘勝軍 * @createTime: 2017年9月13日 下午9:01:42 * @version: v1.0 * @copyright:上海每特教育科技有限公司 * @QQ:644064779 */ @Controller public class TestController { private static final String TEST = "test"; @Autowired private VideoTypeService videoTypeService; @RequestMapping("/test") public String test() { return TEST; } @ResponseBody @RequestMapping("/getViideType") public List<VideoType> getViideType() { System.out.println("listVideoType start"); List<VideoType> listVideoType = videoTypeService.showVideoType(null); System.out.println("listVideoType end"); return listVideoType; } } @Service publicclass VideoTypeServiceImpl implements VideoTypeService { @Autowired private VideoTypeMapper videoTypeMapper; public List<VideoType> showVideoType(VideoType record) { returnvideoTypeMapper.selectList(record); } } public interface VideoTypeMapper { List<VideoType> selectList(VideoType record); } <?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="com.itmayiedu.dao.VideoTypeMapper"> <resultMap id="BaseResultMap" type="com.itmayiedu.entity.VideoType"> <id column="id" property="id" jdbcType="INTEGER" /> <result column="type_name" property="typeName" jdbcType="VARCHAR" /> </resultMap> <sql id="Base_Column_List"> id, type_name </sql> <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer"> select <include refid="Base_Column_List" /> from video_type where id = #{id,jdbcType=INTEGER} </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer"> delete from video_type where id = #{id,jdbcType=INTEGER} </delete> <insert id="insert" parameterType="com.itmayiedu.entity.VideoType"> insert into video_type (id, type_name) values (#{id,jdbcType=INTEGER}, #{typeName,jdbcType=VARCHAR}) </insert> <insert id="insertSelective" parameterType="com.itmayiedu.entity.VideoType"> insert into video_type <trim prefix="(" suffix=")" suffixOverrides=","> <if test="id != null"> id, </if> <if test="typeName != null"> type_name, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides=","> <if test="id != null"> #{id,jdbcType=INTEGER}, </if> <if test="typeName != null"> #{typeName,jdbcType=VARCHAR}, </if> </trim> </insert> <update id="updateByPrimaryKeySelective" parameterType="com.itmayiedu.entity.VideoType"> update video_type <set> <if test="typeName != null"> type_name = #{typeName,jdbcType=VARCHAR}, </if> </set> where id = #{id,jdbcType=INTEGER} </update> <update id="updateByPrimaryKey" parameterType="com.itmayiedu.entity.VideoType"> update video_type set type_name = #{typeName,jdbcType=VARCHAR} where id = #{id,jdbcType=INTEGER} </update> <select id="selectList" resultMap="BaseResultMap" parameterType="com.itmayiedu.entity.VideoType"> select <include refid="Base_Column_List" /> from video_type where 1=1 <if test="id != null"> and #{id,jdbcType=INTEGER}, </if> <if test="typeName != null"> and #{typeName,jdbcType=VARCHAR}, </if>
</select>
</mapper>
|
<!-- 加載spring容器 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/applicationContext-*.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> |
使用SpringMVC返回json格式,返回狀態406,表示SpringMVC沒有集成JSON轉換器
解決辦法:
<!-- 避免IE執行AJAX時,返回JSON出現下載文件 --> <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean>
<!-- 啓動Spring MVC的註解功能,完成請求和註解POJO的映射 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="mappingJacksonHttpMessageConverter" /><!-- json轉換器 --> </list> </property> </bean> |
Ok SpringMVC+Mybatis+Spring+Maven環境整合成功!
在resources/properties下建立log4j.properties文件
### set log levels ### log4j.rootLogger =INFO,DEBUG, stdout , R
log4j.appender.stdout = org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target = System.out log4j.appender.stdout.layout = org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender log4j.appender.D.File = E://logs/log.log log4j.appender.D.Append = true log4j.appender.D.Threshold = DEBUG log4j.appender.D.layout = org.apache.log4j.PatternLayout log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender log4j.appender.E.File =E://logs/error.log log4j.appender.E.Append = true log4j.appender.E.Threshold = ERROR log4j.appender.E.layout = org.apache.log4j.PatternLayout log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
|
<!--設置log4j的配置文件位置 --> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>/WEB-INF/classes/properties/log4j.properties</param-value> </context-param> <!--使用監聽加載log4j的配置文件 --> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> |
使用API
private static Logger log = Logger.getLogger(TestController.class);
步驟:建立JSP頁面,引入C標籤
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> |
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>後臺管理系統</title> </head> <body> <center> <h1>螞蟻視頻後臺管理系統</h1> <a href="locaAddVideo">添加資源</a> <table style="BORDER-COLLAPSE: collapse; text-align: center;" borderColor=#000000 height=40 cellPadding=1 width="70%" align="center" border=1> <thead> <tr> <th>圖片</th> <th>視頻名稱</th> <th>視頻類型</th> <th>預覽視頻</th> </tr> </thead> <tbody> <c:forEach items="${listVideoInfo}" var="p"> <tr style="font-size: 18px"> <td><img alt="" width="150px;" height="150px;" src="/static/imgs/${p.videoUrl}"></td> <td>${p.videoName}</td> <td>${p.typeName}</td> <td><a href="videoDetails?id=${p.id}" style='text-decoration:none;'>預覽視頻</a></td> </tr> </c:forEach>
</tbody> </table>
</center> </body> </html> |
<select id="selectAll" parameterType="com.itmayiedu.entity.VideoInfo" resultType="com.itmayiedu.entity.VideoInfo"> select a.id as id,a.video_name as videoName, a.video_html as videoHtml ,a.video_url as videoUrl, a.video_del as videoDel , b.type_name as typeName from video_info as a inner join video_type as b on a.video_type_id=b.id; </select>
|
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>添加視頻資源</title> </head> <body> <center> <h1>螞蟻視頻後臺添加視頻資源</h1> <form action="addVideo" style="font-size: 14px;" method="post" ENCTYPE="multipart/form-data"> <table> <tr> <td>視頻名稱:</td> <td><input type="text" name=videoName></td> </tr> <tr> <td>視頻類型:</td> <td><select name="videoTypeId" style="width: 170px;"> <c:forEach items="${listVideoType}" var="p"> <option value="${p.id}">${p.typeName}</option> </c:forEach>
</select></td> </tr> <tr> <td>優酷播放URL:</td> <td><textarea rows="10" cols="30" name="videoHtml"></textarea></td> </tr> <tr> <td>上傳封面:</td> <td><input type="file" name="file"></td> </tr> <tr><td colspan="2"><input type="submit" value="提交"></td></tr> </table> </form> </center> </body> </html> |
<!-- 支持上傳文件 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" /> |
@RequestMapping("/addVideo") public String addVideo(@RequestParam(value = "file", required = false) MultipartFile file, VideoInfo videoInfo, HttpServletRequest req, HttpServletResponse res) { try { // 獲取當前上下文 String path = req.getSession().getServletContext().getRealPath("/static/imgs"); // 文件名稱 String newName = System.currentTimeMillis() + ".png"; File targetFile = new File(path, newName); // 文件夾不存在,則建立文件夾 if (!targetFile.exists()) { targetFile.mkdirs(); } // 保存 try { file.transferTo(targetFile); } catch (Exception e) { log.error(e); } videoInfo.setVideoUrl(newName); videoInfoService.addVideoInfo(videoInfo); req.setAttribute("result", "封面上傳成功!"); return"redirect:/videoManag"; } catch (Exception e) { log.error(e); req.setAttribute("result", "上傳失敗!"); returnLOCAVIDEO; }
} |
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>${videoInfo.videoName}視頻詳情</title> </head> <body> <center> <h1>${videoInfo.videoName}</h1> <iframe height=600 width=600 src='${videoInfo.videoHtml}' frameborder=0'allowfullscreen'></iframe> </center>
</body> </html> |
@RequestMapping("/videoDetails") public String videoDetails(intid, HttpServletRequest request) { VideoInfo videoInfo = videoInfoService.getVideoInfo(id); request.setAttribute("videoInfo", videoInfo); returnVIDEODETAILS; } |
<mvc:annotation-driven /> <mvc:resources mapping="/static/imgs/**" location="static/imgs/" /> <mvc:resources mapping="/static/easyui/**" location="static/easyui/" /> <mvc:resources mapping="/static/js/**" location="static/js/" /> <mvc:resources mapping="/static/css/**" location="static/css/" /> |
<?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> <!-- 配置分頁插件 --> <plugins> <plugin interceptor="com.github.pagehelper.PageHelper"> <!-- 設置數據庫類型 Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六種數據庫--> <property name="dialect" value="mysql"/> </plugin> </plugins> </configuration> |
<!-- spring和MyBatis完美整合,不須要mybatis的配置映射文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自動掃描mapping.xml文件 --> <property name="mapperLocations" value="classpath:mappings/*.xml"></property> <property name="configLocation" value="classpath:spring/mybatis-config.xml" /> </bean>
|
@RequestMapping("/indexVideo") public String indexVideo(HttpServletRequest request, int pageIndex) { Page page = PageHelper.startPage(pageIndex, 2); request.setAttribute("listVideo", videoInfoService.getVoideAll(null)); request.setAttribute("pageSize", page.getPages()); return INDEXVIDEO; } |
<a style="font-size: 20px;" href="indexVideo?pageIndex=1">首頁</a> <c:forEach begin="1" end="${pageSize}" var="p"> <a style="font-size: 20px;" href="indexVideo?pageIndex=${p}">${p}</a> </c:forEach> <a style="font-size: 20px;" href="indexVideo?pageIndex=${pageSize}">尾頁</a> |
至此spring基礎知識所有講解完畢