Spring家族愈來愈強大,做爲一名javaWeb開發人員,學習Spring家族的東西是必須的。在此記錄學習Spring-data-jpa的相關知識,方便後續查閱。java
SpringData : Spring 的一個子項目。用於簡化數據庫訪問,支持NoSQL 和 關係數據存儲。其主要目標是使數據庫的訪問變得方便快捷。mysql
SpringData 項目所支持 NoSQL 存儲:spring
- MongoDB (文檔數據庫)
- Neo4j(圖形數據庫)
- Redis(鍵/值存儲)
- Hbase(列族數據庫)
SpringData 項目所支持的關係數據存儲技術:sql
- JDBC
- JPA
JPA Spring Data : 致力於減小數據訪問層 (DAO) 的開發量, 開發者惟一要作的就只是聲明持久層的接口,其餘都交給 Spring Data JPA 來幫你完成!數據庫
框架怎麼可能代替開發者實現業務邏輯呢?好比:當有一個 UserDao.findUserById() 這樣一個方法聲明,大體應該能判斷出這是根據給定條件的 ID 查詢出知足條件的 User 對象。Spring Data JPA 作的即是規範方法的名字,根據符合規範的名字來肯定方法須要實現什麼樣的邏輯。apache
Spring Data JPA 進行持久層(即Dao)開發通常分三個步驟:api
首先咱們在eclipse中建立一個Maven的java項目,而後添加依賴。架構
項目結構見右圖: app
主要依賴有:框架
pom.xml文件的代碼以下
<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.zxy</groupId> <artifactId>springdata-demo</artifactId> <version>0.0.1-SNAPSHOT</version> <!-- 全局屬性配置 --> <properties> <project.source.encoding>utf-8</project.source.encoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <!-- 防止控制輸出臺中文亂碼 --> <argLine>-Dfile.encoding=UTF-8</argLine> </properties> <dependencies> <!-- junit_jar包依賴 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <!--保留到測試 --> <scope>test</scope> </dependency> <!-- spring-data-jpa相關依賴 (這個依賴自動把一堆spring的東西依賴進來了,全部能夠不須要再引入spring的包)--> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-jpa</artifactId> <version>1.11.7.RELEASE</version> </dependency> <!-- Hibernate --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.0.11.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>5.0.11.Final</version> </dependency> <!-- https://mvnrepository.com/artifact/com.mchange/c3p0 --> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.5.2</version> </dependency> <!-- mysql驅動 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.29</version> </dependency> </dependencies> <build> <plugins> <!-- 編譯插件 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.5.1</version> <configuration> <!-- 源碼用1.8 --> <source>1.8</source> <!-- 打成jar用1.8 --> <target>1.8</target> <encoding>utf-8</encoding> </configuration> </plugin> </plugins> </build> </project>
<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.zxy</groupId>
<artifactId>springdata-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<!-- 全局屬性配置 -->
<properties>
<project.source.encoding>utf-8</project.source.encoding>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- 防止控制輸出臺中文亂碼 -->
<argLine>-Dfile.encoding=UTF-8</argLine>
</properties>
<dependencies>
<!-- junit_jar包依賴 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<!--保留到測試 -->
<scope>test</scope>
</dependency>
<!-- spring-data-jpa相關依賴
(這個依賴自動把一堆spring的東西依賴進來了,全部能夠不須要再引入spring的包)-->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.11.7.RELEASE</version>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.0.11.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.0.11.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!-- mysql驅動 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.29</version>
</dependency>
</dependencies>
<build>
<plugins>
<!-- 編譯插件 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<!-- 源碼用1.8 -->
<source>1.8</source>
<!-- 打成jar用1.8 -->
<target>1.8</target>
<encoding>utf-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
jdbcUrl=jdbc:mysql://localhost:3306/springdata?useUnicode=true&characterEncoding=utf8 driverClass=com.mysql.jdbc.Driver user=root password=root initialPoolSize=10 maxPoolSize=30
jdbcUrl=jdbc:mysql://localhost:3306/springdata?useUnicode=true&characterEncoding=utf8
driverClass=com.mysql.jdbc.Driver
user=root
password=root
initialPoolSize=10
maxPoolSize=30
<?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:tx="http://www.springframework.org/schema/tx" xmlns:jpa="http://www.springframework.org/schema/data/jpa" 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/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"> <!-- 配置自動掃描的包,掃描service層,service上面有註解就直接被spring容器實例化 --> <context:component-scan base-package="com.zxy.service"/> <!-- 1. 配置數據源 --> <context:property-placeholder location="classpath:db.properties"/> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="jdbcUrl" value="${jdbcUrl}"/> <property name="driverClass" value="${driverClass}"/> <property name="user" value="${user}"/> <property name="password" value="${password}"/> <property name="initialPoolSize" value="${initialPoolSize}"/> <property name="maxPoolSize" value="${maxPoolSize}"/> </bean> <!-- 2. 配置 JPA 的 EntityManagerFactory --> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="jpaVendorAdapter"> <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"></bean> </property> <!-- 配置包掃描,掃描實體 --> <property name="packagesToScan" value="com.zxy.entity"/> <property name="jpaProperties"> <props> <!-- 生成的數據表的列的映射策略 --> <prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop> <!-- hibernate 基本屬性 --> <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> </props> </property> </bean> <!-- 3. 配置事務管理器 --> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory"/> </bean> <!-- 4. 配置支持註解的事務 --> <tx:annotation-driven transaction-manager="transactionManager"/> <!-- 5. 配置 SpringData,須要加入 jpa 的命名空間 --> <!-- base-package: 掃描 Repository Bean 所在的 package --> <jpa:repositories base-package="com.zxy.dao" entity-manager-factory-ref="entityManagerFactory"> </jpa:repositories> </beans>
<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:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
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/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<!-- 配置自動掃描的包,掃描service層,service上面有註解就直接被spring容器實例化 -->
<context:component-scan base-package="com.zxy.service"/>
<!-- 1. 配置數據源 -->
<context:property-placeholder location="classpath:db.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="jdbcUrl" value="${jdbcUrl}"/>
<property name="driverClass" value="${driverClass}"/>
<property name="user" value="${user}"/>
<property name="password" value="${password}"/>
<property name="initialPoolSize" value="${initialPoolSize}"/>
<property name="maxPoolSize" value="${maxPoolSize}"/>
</bean>
<!-- 2. 配置 JPA 的 EntityManagerFactory -->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"></bean>
</property>
<!-- 配置包掃描,掃描實體 -->
<property name="packagesToScan" value="com.zxy.entity"/>
<property name="jpaProperties">
<props>
<!-- 生成的數據表的列的映射策略 -->
<prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop>
<!-- hibernate 基本屬性 -->
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<!-- 3. 配置事務管理器 -->
<bean id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<!-- 4. 配置支持註解的事務 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- 5. 配置 SpringData,須要加入 jpa 的命名空間 -->
<!-- base-package: 掃描 Repository Bean 所在的 package -->
<jpa:repositories base-package="com.zxy.dao" entity-manager-factory-ref="entityManagerFactory">
</jpa:repositories>
</beans>
package com.zxy.test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import java.sql.SQLException; import javax.sql.DataSource; import org.junit.Test; /** * 整合效果測試類 * @author ZENG.XIAO.YAN * @date 2017年9月14日 下午11:01:20 * @version v1.0 */ public class TestConfig { private static ApplicationContext ctx ; static { // 經過靜態代碼塊的方式,讓程序加載spring的配置文件 ctx = new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); } /** 測試spring容器是否實例化了數據源 。若是實例化了,說明Spring容器整合沒問題 */ @Test public void testDataSouce() throws SQLException { DataSource dataSouce = (DataSource) ctx.getBean("dataSource"); System.out.println("數據源:"+ dataSouce); System.out.println("鏈接:"+ dataSouce.getConnection()); } }
package com.zxy.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.junit.Test;
/**
* 整合效果測試類
* @author ZENG.XIAO.YAN
* @date 2017年9月14日 下午11:01:20
* @version v1.0
*/
public class TestConfig {
private static ApplicationContext ctx ;
static {
// 經過靜態代碼塊的方式,讓程序加載spring的配置文件
ctx = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
}
/** 測試spring容器是否實例化了數據源 。若是實例化了,說明Spring容器整合沒問題 */
public void testDataSouce() throws SQLException {
DataSource dataSouce = (DataSource) ctx.getBean("dataSource");
System.out.println("數據源:"+ dataSouce);
System.out.println("鏈接:"+ dataSouce.getConnection());
}
}
package com.zxy.entity; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; /** * Person實體 * @author ZENG.XIAO.YAN * @date 2017年9月14日 下午2:44:23 * @version v1.0 */ @Entity @Table(name="jpa_persons") public class Person { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Integer id; @Column private String name; @Column private String email; @Column private Date birth; /** setter and getter method */ 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 getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Date getBirth() { return birth; } public void setBirth(Date birth) { this.birth = birth; } }
package com.zxy.entity;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* Person實體
* @author ZENG.XIAO.YAN
* @date 2017年9月14日 下午2:44:23
* @version v1.0
*/
name="jpa_persons") (
public class Person {
(strategy=GenerationType.IDENTITY)
private Integer id;
private String name;
private String email;
private Date birth;
/** setter and getter method */
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 getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
}
package com.zxy.dao; import org.springframework.data.repository.Repository; import org.springframework.data.repository.RepositoryDefinition; import com.zxy.entity.Person; /** * PersonDao * @author ZENG.XIAO.YAN * @date 2017年9月18日 下午4:25:39 * @version v1.0 */ /* * 1.Repository是一個空接口,便是一個標記接口 * 2.若咱們定義的接口繼承了Repository,則該接口會被IOC容器識別爲一個Repository Bean * 注入到IOC容器中,進而能夠在該接口中定義知足必定規則的接口 * 3.實際上也能夠經過一個註解@RepositoryDefination 註解來替代Repository接口 */ //@RepositoryDefinition(domainClass=Person.class,idClass=Integer.class) public interface PersonDao extends Repository<Person, Integer> { // 經過id查找實體 Person getById(Integer id); }
package com.zxy.dao;
import org.springframework.data.repository.Repository;
import org.springframework.data.repository.RepositoryDefinition;
import com.zxy.entity.Person;
/**
* PersonDao
* @author ZENG.XIAO.YAN
* @date 2017年9月18日 下午4:25:39
* @version v1.0
*/
/*
* 1.Repository是一個空接口,便是一個標記接口
* 2.若咱們定義的接口繼承了Repository,則該接口會被IOC容器識別爲一個Repository Bean
* 注入到IOC容器中,進而能夠在該接口中定義知足必定規則的接口
* 3.實際上也能夠經過一個註解@RepositoryDefination 註解來替代Repository接口
*/
//@RepositoryDefinition(domainClass=Person.class,idClass=Integer.class)
public interface PersonDao extends Repository<Person, Integer> {
// 經過id查找實體
Person getById(Integer id);
}
package com.zxy.test; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.zxy.dao.PersonDao; import com.zxy.entity.Person; /** * SpringData快速入門測試類 * @author ZENG.XIAO.YAN * @date 2017年9月18日 下午5:33:42 * @version v1.0 */ public class TestQuickStart { private static ApplicationContext ctx ; static { // 經過靜態代碼塊的方式,讓程序加載spring的配置文件 ctx = new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); } /** 測試PersonDao中定義的getById的方法可否查詢出結果 */ @Test public void testGetById() { PersonDao personDao = ctx.getBean(PersonDao.class); Person person = personDao.getById(1); System.out.println("查詢結果: name=" + person.getName() + ",id=" + person.getId()); } }
package com.zxy.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.zxy.dao.PersonDao;
import com.zxy.entity.Person;
/**
* SpringData快速入門測試類
* @author ZENG.XIAO.YAN
* @date 2017年9月18日 下午5:33:42
* @version v1.0
*/
public class TestQuickStart {
private static ApplicationContext ctx ;
static {
// 經過靜態代碼塊的方式,讓程序加載spring的配置文件
ctx = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
}
/** 測試PersonDao中定義的getById的方法可否查詢出結果 */
public void testGetById() {
PersonDao personDao = ctx.getBean(PersonDao.class);
Person person = personDao.getById(1);
System.out.println("查詢結果: name=" + person.getName() + ",id=" + person.getId());
}
}
// 經過id和name查詢實體,sql: select * from jpa_persons where id = ? and name = ? Person findByIdAndName(Integer id, String name);
// 經過id和name查詢實體,sql: select * from jpa_persons where id = ? and name = ?
Person findByIdAndName(Integer id, String name);
/** 測試getByIdAndName方法 */ @Test public void testGetByIdAndName() { PersonDao personDao = ctx.getBean(PersonDao.class); Person person = personDao.findByIdAndName(1, "test0"); System.out.println(person); }
/** 測試getByIdAndName方法 */
public void testGetByIdAndName() {
PersonDao personDao = ctx.getBean(PersonDao.class);
Person person = personDao.findByIdAndName(1, "test0");
System.out.println(person);
}
// where id < ? or birth < ? List<Person> findByIdIsLessThanOrBirthLessThan(Integer id, Date birth); // where email like ? List<Person> findByEmailLike(String email); // 也支持count查詢 long countByEmailLike(String email);
// where id < ? or birth < ?
List<Person> findByIdIsLessThanOrBirthLessThan(Integer id, Date birth);
// where email like ?
List<Person> findByEmailLike(String email);
// 也支持count查詢
long countByEmailLike(String email);
/** 測試findByEmailLike方法 */ @Test public void testFindByEmailLike() { PersonDao personDao = ctx.getBean(PersonDao.class); List<Person> list = personDao.findByEmailLike("test%"); for (Person person : list) { System.out.println(person.getEmail()); } } /** 測試findByIdIsLessThanOrBirthLessThan方法 */ @Test public void testFindByIdIsLessThanOrBirthLessThan() { PersonDao personDao = ctx.getBean(PersonDao.class); List<Person> list = personDao.findByIdIsLessThanOrBirthLessThan(3, new Date()); for (Person person : list) { System.out.println("查詢結果: name=" + person.getName() + ",id=" + person.getId() + ",birth=" + person.getBirth()); } }
/** 測試findByEmailLike方法 */
public void testFindByEmailLike() {
PersonDao personDao = ctx.getBean(PersonDao.class);
List<Person> list = personDao.findByEmailLike("test%");
for (Person person : list) {
System.out.println(person.getEmail());
}
}
/** 測試findByIdIsLessThanOrBirthLessThan方法 */
public void testFindByIdIsLessThanOrBirthLessThan() {
PersonDao personDao = ctx.getBean(PersonDao.class);
List<Person> list = personDao.findByIdIsLessThanOrBirthLessThan(3, new Date());
for (Person person : list) {
System.out.println("查詢結果: name=" + person.getName()
+ ",id=" + person.getId() + ",birth=" + person.getBirth());
}
}
// 級聯查詢,查詢address的id等於條件值 List<Person> findByAddressId(Integer addressId);
// 級聯查詢,查詢address的id等於條件值
List<Person> findByAddressId(Integer addressId);
/** 測試findByAddressId方法 */ @Test public void testFindByAddressId() { PersonDao personDao = ctx.getBean(PersonDao.class); // 查出地址id爲1的person集合 List<Person> list = personDao.findByAddressId(1); for (Person person : list) { System.out.println(person.getName() + "---addressId=" + person.getAddress().getId()); } }
/** 測試findByAddressId方法 */
public void testFindByAddressId() {
PersonDao personDao = ctx.getBean(PersonDao.class);
// 查出地址id爲1的person集合
List<Person> list = personDao.findByAddressId(1);
for (Person person : list) {
System.out.println(person.getName()
+ "---addressId="
+ person.getAddress().getId());
}
}
// 自定義的查詢,直接寫jpql語句; 查詢id<? 或者 名字 like?的person集合 @Query("from Person where id < ?1 or name like ?2") List<Person> testPerson(Integer id, String name); // 自定義查詢之子查詢,直接寫jpql語句; 查詢出id最大的person @Query("from Person where id = (select max(p.id) from Person as p)") Person testSubquery();
// 自定義的查詢,直接寫jpql語句; 查詢id<? 或者 名字 like?的person集合
"from Person where id < ?1 or name like ?2") (
List<Person> testPerson(Integer id, String name);
// 自定義查詢之子查詢,直接寫jpql語句; 查詢出id最大的person
"from Person where id = (select max(p.id) from Person as p)") (
Person testSubquery();
/** 測試用Query註解自定義的方法 */ @Test public void testCustomMethod() { PersonDao personDao = ctx.getBean(PersonDao.class); List<Person> list = personDao.testPerson(2, "%admin%"); for (Person person : list) { System.out.println("查詢結果: name=" + person.getName() + ",id=" + person.getId()); } System.out.println("===============分割線==============="); Person person = personDao.testSubquery(); System.out.println("查詢結果: name=" + person.getName() + ",id=" + person.getId()); }
/** 測試用Query註解自定義的方法 */
public void testCustomMethod() {
PersonDao personDao = ctx.getBean(PersonDao.class);
List<Person> list = personDao.testPerson(2, "%admin%");
for (Person person : list) {
System.out.println("查詢結果: name=" + person.getName() + ",id=" + person.getId());
}
System.out.println("===============分割線===============");
Person person = personDao.testSubquery();
System.out.println("查詢結果: name=" + person.getName() + ",id=" + person.getId());
}
//能夠經過自定義的 JPQL 完成 UPDATE 和 DELETE 操做. 注意: JPQL 不支持使用 INSERT //在 @Query 註解中編寫 JPQL 語句, 但必須使用 @Modifying 進行修飾. 以通知 SpringData, 這是一個 UPDATE 或 DELETE 操做 //UPDATE 或 DELETE 操做須要使用事務, 此時須要定義 Service 層. 在 Service 層的方法上添加事務操做. //默認狀況下, SpringData 的每一個方法上有事務, 但都是一個只讀事務. 他們不能完成修改操做! @Modifying @Query("UPDATE Person p SET p.name = :name WHERE p.id < :id") int updatePersonById(@Param("id")Integer id, @Param("name")String updateName);
//能夠經過自定義的 JPQL 完成 UPDATE 和 DELETE 操做. 注意: JPQL 不支持使用 INSERT
//在 @Query 註解中編寫 JPQL 語句, 但必須使用 @Modifying 進行修飾. 以通知 SpringData, 這是一個 UPDATE 或 DELETE 操做
//UPDATE 或 DELETE 操做須要使用事務, 此時須要定義 Service 層. 在 Service 層的方法上添加事務操做.
//默認狀況下, SpringData 的每一個方法上有事務, 但都是一個只讀事務. 他們不能完成修改操做!
"UPDATE Person p SET p.name = :name WHERE p.id < :id") (
int updatePersonById( ("id")Integer id, ("name")String updateName);
package com.zxy.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.zxy.dao.PersonDao; /** * PersonService * @author ZENG.XIAO.YAN * @date 2017年9月20日 下午2:57:16 * @version v1.0 */ @Service("personService") public class PersonService { @Autowired private PersonDao personDao; @Transactional(readOnly=false) public int updatePersonById(Integer id, String updateName) { return personDao.updatePersonById(id, updateName); } }
package com.zxy.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.zxy.dao.PersonDao;
/**
* PersonService
* @author ZENG.XIAO.YAN
* @date 2017年9月20日 下午2:57:16
* @version v1.0
*/
"personService") (
public class PersonService {
private PersonDao personDao;
(readOnly=false)
public int updatePersonById(Integer id, String updateName) {
return personDao.updatePersonById(id, updateName);
}
}