Spring Data Jpa --- 入门
一、概述
Spring Data是Spring下的一个子项目,用于简化数据库访问,并支持云服务的开源框架。Spring Data支持NoSQL和 关系数据存储,其主要目标是使得数据库的访问变得方便快捷。并支持map-reduce框架和云计算数据服务。对于拥有海量数据的项目,可以用Spring Data来简化项目的开发。 然而针对不同的数据储存访问使用相对的类库来操作访问。Spring Data中已经为我们提供了很多业务中常用的一些接口和实现类来帮我们快速构建项目,比如分页、排序、DAO一些常用的操作。
二、环境搭建
1.1 导入jar包
1.2 applicationContext.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: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.xsdhttp://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"><!-- 配置自动扫描的包 --><context:component-scan base-package="com.test.springdata"></context:component-scan><!-- 1. 配置数据源 --><context:property-placeholder location="classpath:config.properties"/><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><property name="driverClass" value="${jdbc.driver}" /><property name="jdbcUrl" value="${jdbc.url}" /><property name="user" value="${jdbc.user}" /><property name="password" value="${jdbc.password}" /></bean><!-- 2. 配置 JPA 的 EntityManagerFactory --><bean id="entityManagerFactory"class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"><property name="dataSource" ref="dataSource"></property><property name="jpaVendorAdapter"><bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"></bean></property><property name="packagesToScan" value="com.test.springdata"></property><property name="jpaProperties"><props><!-- 二级缓存相关 --><!-- <prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop><prop key="net.sf.ehcache.configurationResourceName">ehcache-hibernate.xml</prop> --><!-- 生成的数据表的列的映射策略 --><prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop><!-- hibernate 基本属性 --><prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</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"></property></bean><!-- 4. 配置支持注解的事务 --><tx:annotation-driven transaction-manager="transactionManager"/><!-- 5. 配置 SpringData --><!-- 加入 jpa 的命名空间 --><!-- base-package: 扫描 Repository Bean 所在的 package --><jpa:repositories base-package="com.test.springdata"entity-manager-factory-ref="entityManagerFactory"></jpa:repositories></beans>
三、Repository接口
Repository 接口是 Spring Data 的一个核心接口,它不提供任何方法,开发者需要在自己定义的接口中声明需要的方法。
public interface Repository<T, ID extends Serializable> {}
说明:
- Repository是一个空接口,即是一个标记接口
- 若我们定义的接口继承了Repository,则该接口会被IOC容器识别为一个Repository Bean注入到IOC容器中,只要遵循Spring Data的方法定义规范,就无需写实现类。
- 与继承 Repository 等价的一种方式,就是在持久层接口上使用 @RepositoryDefinition 注解,并为其指定 domainClass 和 idClass 属性。如下两种方式是完全等价的
@RepositoryDefinition(domainClass=Person.class,idClass=Integer.class)
3.1 Repository的子接口
基础的 Repository 提供了最基本的数据访问功能,其几个子接口则扩展了一些功能。它们的继承关系如下:
- Repository: 仅仅是一个标识,表明任何继承它的均为仓库接口类
- CrudRepository: 继承 Repository,实现了一组 CRUD 相关的方法
- PagingAndSortingRepository: 继承 CrudRepository,实现了一组分页排序相关的方法
- JpaRepository: 继承 PagingAndSortingRepository,实现一组 JPA 规范相关的方法
3.2 Spring Data方法定义规范
查询方法以find | read | get开头,设计条件查询时,条件的属性用条件关键字连接,要注意的是:条件属性以首字母大写。
例如:定义一个 Entity 实体类
class User{private String firstName;private String lastName;}
使用And条件连接时,应这样写:
findByLastNameAndFirstName(String lastName,String firstName);
条件的属性名称与个数要与参数的位置与个数一一对应
直接在接口中定义查询方法,如果是符合规范的,可以不用写实现,目前支持的关键字写法如下:
三、CrudRepository接口
CrudRepository 接口提供了最基本的对实体类的添删改查操作
- T save(T entity);//保存单个实体
- Iterable<T> save(Iterable<? extends T> entities);//保存集合
- T findOne(ID id);//根据id查找实体
- boolean exists(ID id);//根据id判断实体是否存在
- Iterable<T> findAll();//查询所有实体,不用或慎用!
- long count();//查询实体数量
- void delete(ID id);//根据Id删除实体
- void delete(T entity);//删除一个实体
- void delete(Iterable<? extends T> entities);//删除一个实体的集合
- void deleteAll();//删除所有实体,不用或慎用!
四、PagingAndSortingRepository接口
PagingAndSortingRepository接口提供了分页与排序的功能:
- Iterable<T> findAll(Sort sort); //排序
- Page<T> findAll(Pageable pageable); //分页查询(含排序功能)
五、JpaRepository接口
JpaRepository接口提供了JPA的相关功能:
- List<T> findAll(); //查找所有实体
- List<T> findAll(Sort sort); //排序、查找所有实体
- List<T> save(Iterable<? extends T> entities);//保存集合
- void flush();//执行缓存与数据库同步
- T saveAndFlush(T entity);//强制执行持久化
- void deleteInBatch(Iterable<T> entities);//删除一个实体集合
示例代码
Person实体类
package com.test.springdata;import java.util.Date;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.persistence.JoinColumn;import javax.persistence.ManyToOne;import javax.persistence.Table;@Table(name="JPA_PERSONS")@Entitypublic class Person {private Integer id;private String lastName;private String email;private Date birth;private Address address;private Integer addressId;@GeneratedValue@Idpublic Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getLastName() {return lastName;}public void setLastName(String lastName) {this.lastName = lastName;}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;}@Column(name="ADD_ID")public Integer getAddressId() {return addressId;}public void setAddressId(Integer addressId) {this.addressId = addressId;}@JoinColumn(name="ADDRESS_ID")@ManyToOnepublic Address getAddress() {return address;}public void setAddress(Address address) {this.address = address;}@Overridepublic String toString() {return "Person [id=" + id + ", lastName=" + lastName + ", email="+ email + ", brith=" + birth + "]";}}
Address实体类
package com.test.springdata;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.persistence.Table;@Table(name="JPA_ADDRESSES")@Entitypublic class Address {private Integer id;private String province;private String city;@GeneratedValue@Idpublic Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getProvince() {return province;}public void setProvince(String province) {this.province = province;}public String getCity() {return city;}public void setCity(String city) {this.city = city;}}
JpaRepsotory类 --- PersonRepsotory类
package com.test.springdata;import java.util.Date;import java.util.List;import org.springframework.data.jpa.repository.JpaRepository;import org.springframework.data.jpa.repository.JpaSpecificationExecutor;import org.springframework.data.jpa.repository.Modifying;import org.springframework.data.jpa.repository.Query;import org.springframework.data.repository.CrudRepository;import org.springframework.data.repository.PagingAndSortingRepository;import org.springframework.data.repository.Repository;import org.springframework.data.repository.RepositoryDefinition;import org.springframework.data.repository.query.Param;/*** 1、Repository 是一个空接口,即使一个标记接口* 2、若我们定义的接口继承了Repository,则该接口会被IOC容器识别为一个Repository Bean* 纳入到IOC容器中,进而可以在该接口中定义满足一定规范的方法* 3、可以通过注解的方式标记Repository接口*//*** 方式一:继承Repository<Person,Integer>接口* public interface PersonRepsotory extends Repository<Person,Integer>{* *//*** 方式二:注解@RepositoryDefinition(domainClass=Person.class,idClass=Integer.class)**//*** 在Repository子接口中声明方法* 1、不是随便声明的,而需要符合一定的规范* 2、查询方法以find | read | get开头* 3、涉及条件查询时,条件的属性用条件关键字连接* 4、要注意的是:条件属性以首字母大写* 5、支持属性的级联查询,若当前类有符合条件的属性,则优先使用,而不使用级联属性。若需要使用级联属性,则属性之间使用_连接**/// @RepositoryDefinition(domainClass=Person.class,idClass=Integer.class)//public interface PersonRepsotory extends Repository<Person, Integer>{//public interface PersonRepsotory extends CrudRepository<Person, Integer>{//public interface PersonRepsotory extends JpaRepository<Person, Integer>,JpaSpecificationExecutor<Person>{public interface PersonRepsotory extends Repository<Person, Integer>{// 根据lastName来获取对应的PersonPerson getByLastName(String lastName);// Where lastName like ?% And id < ?List<Person> getByLastNameStartingWithAndIdLessThan(String lastName, Integer id);// Where lastName like %? And id < ?List<Person> getByLastNameEndingWithAndIdLessThan(String lastName, Integer id);//WHERE email IN (?, ?, ?) OR birth < ?List<Person> getByEmailInAndBirthLessThan(List<String> emails, Date birth);//WHERE a.id > ?List<Person> getByAddress_IdGreaterThan(Integer id);//查询 id 值最大的那个 Person//使用 @Query 注解可以自定义 JPQL 语句以实现更灵活的查询@Query("SELECT p FROM Person p WHERE p.id = (SELECT max(p2.id) FROM Person p2)")Person getMaxIdPerson();//为 @Query 注解传递参数的方式1: 使用占位符.@Query("SELECT p FROM Person p WHERE p.lastName = ?1 AND p.email = ?2")List<Person> testQueryAnnotationParams1(String lastName, String email);//为 @Query 注解传递参数的方式1: 命名参数的方式.@Query("SELECT p FROM Person p WHERE p.lastName = :lastName AND p.email = :email")List<Person> testQueryAnnotationParams2(@Param("email") String email, @Param("lastName") String lastName);//SpringData 允许在占位符上添加 %%.@Query("SELECT p FROM Person p WHERE p.lastName LIKE %?1% OR p.email LIKE %?2%")List<Person> testQueryAnnotationLikeParam(String lastName, String email);//SpringData 允许在占位符上添加 %%.@Query("SELECT p FROM Person p WHERE p.lastName LIKE %:lastName% OR p.email LIKE %:email%")List<Person> testQueryAnnotationLikeParam2(@Param("email") String email, @Param("lastName") String lastName);//设置 nativeQuery=true 即可以使用原生的 SQL 查询@Query(value="SELECT count(id) FROM jpa_persons", nativeQuery=true)long getTotalCount();//可以通过自定义的 JPQL 完成 UPDATE 和 DELETE 操作. 注意: JPQL 不支持使用 INSERT//在 @Query 注解中编写 JPQL 语句, 但必须使用 @Modifying 进行修饰. 以通知 SpringData, 这是一个 UPDATE 或 DELETE 操作//UPDATE 或 DELETE 操作需要使用事务, 此时需要定义 Service 层. 在 Service 层的方法上添加事务操作.//默认情况下, SpringData 的每个方法上有事务, 但都是一个只读事务. 他们不能完成修改操作!@Modifying@Query("UPDATE Person p SET p.email = :email WHERE id = :id")void updatePersonEmail(@Param("id") Integer id, @Param("email") String email);}
PersonService类
package com.test.springdata;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;@Servicepublic class PersonService {@Autowiredprivate PersonRepsotory personRepsotory;@Transactionalpublic void savePersons(List<Person> persons){personRepsotory.save(persons);}@Transactionalpublic void updatePersonEmail(String email, Integer id){personRepsotory.updatePersonEmail(id, email);}}
Test类
package com.test.springdata.test;import java.io.FileNotFoundException;import java.io.IOException;import java.sql.SQLException;import java.util.ArrayList;import java.util.Arrays;import java.util.Date;import java.util.List;import javax.persistence.criteria.CriteriaBuilder;import javax.persistence.criteria.CriteriaQuery;import javax.persistence.criteria.Path;import javax.persistence.criteria.Predicate;import javax.persistence.criteria.Root;import javax.sql.DataSource;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import org.springframework.data.domain.Page;import org.springframework.data.domain.PageRequest;import org.springframework.data.domain.Sort;import org.springframework.data.domain.Sort.Direction;import org.springframework.data.domain.Sort.Order;import org.springframework.data.jpa.domain.Specification;import com.test.springdata.Person;import com.test.springdata.PersonRepsotory;import com.test.springdata.PersonService;public class SpringDataTest {private ApplicationContext ctx = null;private PersonRepsotory personRepsotory = null;private PersonService personService;{ctx = new ClassPathXmlApplicationContext("applicationContext.xml");personRepsotory = ctx.getBean(PersonRepsotory.class);personService = ctx.getBean(PersonService.class);}/*@Testpublic void testCommonCustomRepositoryMethod(){ApplicationContext ctx2 = new ClassPathXmlApplicationContext("classpath:com/atguigu/springdata/commonrepositorymethod/applicationContext2.xml");AddressRepository addressRepository = ctx2.getBean(AddressRepository.class);addressRepository.method();}@Testpublic void testCustomRepositoryMethod(){personRepsotory.test();}*//*** 目标: 实现带查询条件的分页. id > 5 的条件** 调用 JpaSpecificationExecutor 的 Page<T> findAll(Specification<T> spec, Pageable pageable);* Specification: 封装了 JPA Criteria 查询的查询条件* Pageable: 封装了请求分页的信息: 例如 pageNo, pageSize, Sort*//*@Testpublic void testJpaSpecificationExecutor(){int pageNo = 3 - 1;int pageSize = 5;PageRequest pageable = new PageRequest(pageNo, pageSize);//通常使用 Specification 的匿名内部类Specification<Person> specification = new Specification<Person>() {*//*** @param *root: 代表查询的实体类.* @param query: 可以从中可到 Root 对象, 即告知 JPA Criteria 查询要查询哪一个实体类. 还可以* 来添加查询条件, 还可以结合 EntityManager 对象得到最终查询的 TypedQuery 对象.* @param *cb: CriteriaBuilder 对象. 用于创建 Criteria 相关对象的工厂. 当然可以从中获取到 Predicate 对象* @return: *Predicate 类型, 代表一个查询条件.*//*@Overridepublic Predicate toPredicate(Root<Person> root,CriteriaQuery<?> query, CriteriaBuilder cb) {Path path = root.get("id");Predicate predicate = cb.gt(path, 5);return predicate;}};Page<Person> page = personRepsotory.findAll(specification, pageable);System.out.println("总记录数: " + page.getTotalElements());System.out.println("当前第几页: " + (page.getNumber() + 1));System.out.println("总页数: " + page.getTotalPages());System.out.println("当前页面的 List: " + page.getContent());System.out.println("当前页面的记录数: " + page.getNumberOfElements());}*//*@Testpublic void testJpaRepository(){Person person = new Person();person.setBirth(new Date());person.setEmail("xy@atguigu.com");person.setLastName("xyz");Person person2 = personRepsotory.saveAndFlush(person);System.out.println(person == person2);}*//*@Testpublic void testPagingAndSortingRespository(){//pageNo 从 0 开始.int pageNo = 0;int pageSize = 5;//Pageable 接口通常使用的其 PageRequest 实现类. 其中封装了需要分页的信息//排序相关的. Sort 封装了排序的信息//Order 是具体针对于某一个属性进行升序还是降序.Order order1 = new Order(Direction.DESC, "id");Order order2 = new Order(Direction.ASC, "email");Sort sort = new Sort(order1, order2);PageRequest pageable = new PageRequest(pageNo, pageSize, sort);Page<Person> page = personRepsotory.findAll(pageable);System.out.println("总记录数: " + page.getTotalElements());System.out.println("当前第几页: " + (page.getNumber() + 1));System.out.println("总页数: " + page.getTotalPages());System.out.println("当前页面的 List: " + page.getContent());System.out.println("当前页面的记录数: " + page.getNumberOfElements());}*/@Testpublic void testCrudReposiory(){List<Person> persons = new ArrayList<>();for(int i = 'a'; i <= 'z'; i++){Person person = new Person();person.setAddressId(i + 1);person.setBirth(new Date());person.setEmail((char)i + "" + (char)i + "@atguigu.com");person.setLastName((char)i + "" + (char)i);persons.add(person);}personService.savePersons(persons);}@Testpublic void testModifying(){// personRepsotory.updatePersonEmail(1, "mmmm@atguigu.com");personService.updatePersonEmail("mmmm@atguigu.com", 1);}@Testpublic void testNativeQuery(){long count = personRepsotory.getTotalCount();System.out.println(count);}@Testpublic void testQueryAnnotationLikeParam(){// List<Person> persons = personRepsotory.testQueryAnnotationLikeParam("%A%", "%bb%");// System.out.println(persons.size());// List<Person> persons = personRepsotory.testQueryAnnotationLikeParam("A", "bb");// System.out.println(persons.size());List<Person> persons = personRepsotory.testQueryAnnotationLikeParam2("bb", "A");System.out.println(persons.size());}@Testpublic void testQueryAnnotationParams2(){List<Person> persons = personRepsotory.testQueryAnnotationParams2("aa@atguigu.com", "AA");System.out.println(persons);}@Testpublic void testQueryAnnotationParams1(){List<Person> persons = personRepsotory.testQueryAnnotationParams1("AA", "aa@atguigu.com");System.out.println(persons);}@Testpublic void testQueryAnnotation(){Person person = personRepsotory.getMaxIdPerson();System.out.println(person);}@Testpublic void testKeyWords2(){List<Person> persons = personRepsotory.getByAddress_IdGreaterThan(1);System.out.println(persons);}@Testpublic void testKeyWords(){List<Person> persons = personRepsotory.getByLastNameStartingWithAndIdLessThan("X", 10);System.out.println(persons);persons = personRepsotory.getByLastNameEndingWithAndIdLessThan("X", 10);System.out.println(persons);persons = personRepsotory.getByEmailInAndBirthLessThan(Arrays.asList("AA@atguigu.com", "FF@atguigu.com","SS@atguigu.com"), new Date());System.out.println(persons.size());}@Testpublic void testHelloWorldSpringData() throws FileNotFoundException, IOException, InstantiationException, IllegalAccessException{System.out.println(personRepsotory.getClass().getName());Person person = personRepsotory.getByLastName("AA");System.out.println(person);}@Testpublic void testJpa(){}@Testpublic void testDataSource() throws SQLException {DataSource dataSource = ctx.getBean(DataSource.class);System.out.println(dataSource.getConnection());}}
六、JpaSpecificationExecutor接口
不属于Repository体系,实现一组 JPA Criteria 查询相关的方法
Specification:封装 JPA Criteria 查询条件。
通常使用匿名内部类的方式来创建该接口的对象
示例代码:
Test代码,其他代码参考JpaRepository
/*** 目标: 实现带查询条件的分页. id > 5 的条件** 调用 JpaSpecificationExecutor 的 Page<T> findAll(Specification<T> spec, Pageable pageable);* Specification: 封装了 JPA Criteria 查询的查询条件* Pageable: 封装了请求分页的信息: 例如 pageNo, pageSize, Sort*/@Testpublic void testJpaSpecificationExecutor(){int pageNo = 3 - 1;int pageSize = 5;PageRequest pageable = new PageRequest(pageNo, pageSize);//通常使用 Specification 的匿名内部类Specification<Person> specification = new Specification<Person>() {/*** @param *root: 代表查询的实体类.* @param query: 可以从中可到 Root 对象, 即告知 JPA Criteria 查询要查询哪一个实体类. 还可以* 来添加查询条件, 还可以结合 EntityManager 对象得到最终查询的 TypedQuery 对象.* @param *cb: CriteriaBuilder 对象. 用于创建 Criteria 相关对象的工厂. 当然可以从中获取到 Predicate 对象* @return: *Predicate 类型, 代表一个查询条件.*/@Overridepublic Predicate toPredicate(Root<Person> root,CriteriaQuery<?> query, CriteriaBuilder cb) {Path path = root.get("id");Predicate predicate = cb.gt(path, 5);return predicate;}};Page<Person> page = personRepsotory.findAll(specification, pageable);System.out.println("总记录数: " + page.getTotalElements());System.out.println("当前第几页: " + (page.getNumber() + 1));System.out.println("总页数: " + page.getTotalPages());System.out.println("当前页面的 List: " + page.getContent());System.out.println("当前页面的记录数: " + page.getNumberOfElements());}
七、自定义Repository接口
步骤:
- 定义一个接口: 声明要添加的, 并自实现的方法
- 提供该接口的实现类: 类名需在要声明的 Repository 后添加 Impl, 并实现方法
- 声明 Repository 接口, 并继承 1) 声明的接口使用。
注意: 默认情况下, Spring Data 会在 base-package 中查找 "接口名Impl" 作为实现类. 也可以通过repository-impl-postfix 声明后缀
示例代码:
PersonDao接口
package com.test.springdata;public interface PersonDao {void test();}
PersonDao实现类
package com.test.springdata;import javax.persistence.EntityManager;import javax.persistence.PersistenceContext;public class PersonRepsotoryImpl implements PersonDao {@PersistenceContextprivate EntityManager entityManager;@Overridepublic void test() {Person person = entityManager.find(Person.class, 11);System.out.println("-->" + person);}}
PersonRepository类需要继承PersonDao接口
Test方法
@Testpublic void testCustomRepositoryMethod(){personRepsotory.test();}
八、@Query注解
8.1 使用@Query自定义查询,这种查询可以声明在Repository方法中,摆脱像命名查询那样的约束,将查询直接在响应的接口方法中声明,结构更为清晰,这是Spring data的特有实现。
//为 @Query 注解传递参数的方式1: 命名参数的方式.@Query("SELECT p FROM Person p WHERE p.lastName = :lastName AND p.email = :email")List<Person> testQueryAnnotationParams2(@Param("email") String email, @Param("lastName") String lastName);
8.2 使用@Query的nativeQuery=true,这样可以使用原生的SQL查询
//设置 nativeQuery=true 即可以使用原生的 SQL 查询@Query(value="SELECT count(id) FROM jpa_persons", nativeQuery=true)long getTotalCount();
注:详细内容参考JpaRepository示例代码
九、@Modifying注解
在 @Query 注解中编写 JPQL 语句, 但必须使用 @Modifying 进行修饰. 以通知 SpringData, 这是一个 UPDATE 或 DELETE 操作
//可以通过自定义的 JPQL 完成 UPDATE 和 DELETE 操作. 注意: JPQL 不支持使用 INSERT//在 @Query 注解中编写 JPQL 语句, 但必须使用 @Modifying 进行修饰. 以通知 SpringData, 这是一个 UPDATE 或 DELETE 操作//UPDATE 或 DELETE 操作需要使用事务, 此时需要定义 Service 层. 在 Service 层的方法上添加事务操作.//默认情况下, SpringData 的每个方法上有事务, 但都是一个只读事务. 他们不能完成修改操作!@Modifying@Query("UPDATE Person p SET p.email = :email WHERE id = :id")void updatePersonEmail(@Param("id") Integer id, @Param("email") String email);
注意:在调用的地方必须加事务,没有事务不能正常执行
Spring Data Jpa --- 入门的更多相关文章
- spring data jpa入门学习
本文主要介绍下spring data jpa,主要聊聊为何要使用它进行开发以及它的基本使用.本文主要是入门介绍,并在最后会留下完整的demo供读者进行下载,从而了解并且开始使用spring data ...
- Spring Data Jpa 入门学习
本文主要讲解 springData Jpa 入门相关知识, 了解JPA规范与Jpa的实现,搭建springboot+dpringdata jpa环境实现基础增删改操作,适合新手学习,老鸟绕道~ 1. ...
- Spring Data JPA入门及深入
一:Spring Data JPA简介 Spring Data JPA 是 Spring 基于 ORM 框架.JPA 规范的基础上封装的一套JPA应用框架,可使开发者用极简的代码即可实现对数据库的访问 ...
- Spring Data JPA 入门Demo
什么是JPA呢? 其实JPA可以说是一种规范,是java5.0之后提出来的用于持久化的一套规范:它不是任何一种ORM框架,在我看来,是现有ORM框架在这个规范下去实现持久层. 它的出现是为了简化现有的 ...
- Spring Data JPA入门
1. Spring Data JPA是什么 它是Spring基于ORM框架.JPA规范封装的一套JPA应用框架,可使开发者用极简的代码即可实现对数据的访问和操作.它提供了包括增删改查等在内的常用功能, ...
- Spring Data JPA 入门篇
Spring Data JPA是什么 它是Spring基于ORM框架(如hibernate,Mybatis等).JPA规范(Java Persistence API)封装的一套 JPA应用框架,可使开 ...
- 【ORM框架】Spring Data JPA(一)-- 入门
本文参考:spring Data JPA入门 [原创]纯干货,Spring-data-jpa详解,全方位介绍 Spring Data JPA系列教程--入门 一.Spring Data JPA介 ...
- 深入浅出学Spring Data JPA
第一章:Spring Data JPA入门 Spring Data是什么 Spring Data是一个用于简化数据库访问,并支持云服务的开源框架.其主要目标是使得对数据的访问变得方便快捷,并支持map ...
- Spring Data JPA 教程(翻译)
写那些数据挖掘之类的博文 写的比较累了,现在翻译一下关于spring data jpa的文章,觉得轻松多了. 翻译正文: 你有木有注意到,使用Java持久化的API的数据访问代码包含了很多不必要的模式 ...
随机推荐
- LG1955 [NOI2015]程序自动分析
题意 题目描述 在实现程序自动分析的过程中,常常需要判定一些约束条件是否能被同时满足. 考虑一个约束满足问题的简化版本:假设x1,x2,x3...代表程序中出现的变量,给定n个形如xi=xj或xi≠x ...
- android 发送UDP广播,搜寻server建立socket链接
应用场景:client(手机.pc)须要搜寻所在局域网内的server并获得server地址. 方法简单介绍:client发送UDP广播,服务收到广播后得到clientip地址,然后向client发送 ...
- APP自动化测试各项指标分析
一.内存分析专项 启动App. DDMS->update heap 操作app,点几次GC dump heap hprof-conv转化 MAT分析 二.区分几种内存 VSS- Virtual ...
- Huawei E1750 Asterisk
http://wiki.e1550.mobi/doku.php?id=installation https://wiki.asterisk.org/wiki/display/AST/Mobile+Ch ...
- 在浏览器中输入一个URL后都发生了什么
这道题目没有所谓的完全的正确答案,这个题目可以让你在任意的一个点深入下去, 只要你对这个点是熟悉的.以下是一个大概流程: 浏览器向DNS服务器查找输入URL对应的IP地址. DNS服务器返回网站的IP ...
- maven 知识点2
maven 命令: table th:first-of-type { width: 500px; } table th:nth-of-type(2) { } 命令 含义 mvn help:effect ...
- vs2010开发环境恢复--(mysql,数据文件可直接拷贝,并可用navicat直接管理)
一.linq to mysql (DBLINQ) 1.安装mysql phpstudy2014,数据库文件可直接拷贝,在命令行中运行select version();查看版本为5.5.38 ,单独安装 ...
- php 5.2.17 升级到5.3.29
修改php.ini配置文件 register_globals =On include_path = ".;d:/testoa/webroot" error_reporting = ...
- winform 程序调用及参数调用
调用程序: // 新轮廓 -> 调用轮廓扫描程序 private void toolStripMenuItem9_Click(object sender, EventArgs e) ...
- MySQL索引分类和各自用途
一. MySQL: 索引以B树格式保存 Memory存储引擎可以选择Hash或BTree索引,Hash索引只能用于=或<=>的等式比较. 1.普通索引:create index on Ta ...