jpa+springdata
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了jpa+springdata相关的知识,希望对你有一定的参考价值。
学习爱酷学习网尚硅谷springdata笔记:
1.在 Spring 配置文件
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:tx="http://www.springframework.org/schema/tx" 6 xmlns:jpa="http://www.springframework.org/schema/data/jpa" 7 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 8 http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd 9 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd 10 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> 11 12 <!-- 配置自动扫描的包 --> 13 <context:component-scan base-package="com.atguigu.springdata"></context:component-scan> 14 15 <!-- 1. 配置数据源 --> 16 <context:property-placeholder location="classpath:db.properties"/> 17 18 <bean id="dataSource" 19 class="com.mchange.v2.c3p0.ComboPooledDataSource"> 20 <property name="user" value="${jdbc.user}"></property> 21 <property name="password" value="${jdbc.password}"></property> 22 <property name="driverClass" value="${jdbc.driverClass}"></property> 23 <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property> 24 25 <!-- 配置其他属性 --> 26 </bean> 27 28 <!-- 2. 配置 JPA 的 EntityManagerFactory --> 29 <bean id="entityManagerFactory" 30 class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> 31 <property name="dataSource" ref="dataSource"></property> 32 <property name="jpaVendorAdapter"> 33 <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"></bean> 34 </property> 35 <property name="packagesToScan" value="com.atguigu.springdata"></property> 36 <property name="jpaProperties"> 37 <props> 38 <!-- 二级缓存相关 --> 39 <!-- 40 <prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop> 41 <prop key="net.sf.ehcache.configurationResourceName">ehcache-hibernate.xml</prop> 42 --> 43 <!-- 生成的数据表的列的映射策略 --> 44 <prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop> 45 <!-- hibernate 基本属性 --> 46 <prop key="hibernate.dialect">org.hibernate.dialect.mysql5InnoDBDialect</prop> 47 <prop key="hibernate.show_sql">true</prop> 48 <prop key="hibernate.format_sql">true</prop> 49 <prop key="hibernate.hbm2ddl.auto">update</prop> 50 </props> 51 </property> 52 </bean> 53 54 <!-- 3. 配置事务管理器 --> 55 <bean id="transactionManager" 56 class="org.springframework.orm.jpa.JpaTransactionManager"> 57 <property name="entityManagerFactory" ref="entityManagerFactory"></property> 58 </bean> 59 60 <!-- 4. 配置支持注解的事务 --> 61 <tx:annotation-driven transaction-manager="transactionManager"/> 62 63 <!-- 5. 配置 SpringData --> 64 <!-- 加入 jpa 的命名空间 --> 65 <!-- base-package: 扫描 Repository Bean 所在的 package --> 66 <jpa:repositories base-package="com.atguigu.springdata" 67 entity-manager-factory-ref="entityManagerFactory"></jpa:repositories> 68 69 </beans>
其中db.properties
1 jdbc.user=root 2 jdbc.password=1111 3 jdbc.driverClass=com.mysql.jdbc.Driver 4 jdbc.jdbcUrl=jdbc:mysql://localhost:3306/springdata
测试类:
1 package com.atguigu.springdata.test; 2 3 import java.io.FileNotFoundException; 4 import java.io.IOException; 5 import java.sql.SQLException; 6 import java.util.ArrayList; 7 import java.util.Arrays; 8 import java.util.Date; 9 import java.util.List; 10 11 import javax.persistence.criteria.CriteriaBuilder; 12 import javax.persistence.criteria.CriteriaQuery; 13 import javax.persistence.criteria.Path; 14 import javax.persistence.criteria.Predicate; 15 import javax.persistence.criteria.Root; 16 import javax.sql.DataSource; 17 18 import org.junit.Test; 19 import org.springframework.context.ApplicationContext; 20 import org.springframework.context.support.ClassPathXmlApplicationContext; 21 import org.springframework.data.domain.Page; 22 import org.springframework.data.domain.PageRequest; 23 import org.springframework.data.domain.Sort; 24 import org.springframework.data.domain.Sort.Direction; 25 import org.springframework.data.domain.Sort.Order; 26 import org.springframework.data.jpa.domain.Specification; 27 28 import com.atguigu.springdata.Person; 29 import com.atguigu.springdata.PersonRepsotory; 30 import com.atguigu.springdata.PersonService; 31 import com.atguigu.springdata.commonrepositorymethod.AddressRepository; 32 33 public class SpringDataTest { 34 35 private ApplicationContext ctx = null; 36 private PersonRepsotory personRepsotory = null; 37 private PersonService personService; 38 39 { 40 ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); 41 personRepsotory = ctx.getBean(PersonRepsotory.class); 42 personService = ctx.getBean(PersonService.class); 43 } 44 45 46 //使用自定义的方法,需要声明接口,并继承,同时完成实现类,此方法比较少用 47 @Test 48 public void testCustomRepositoryMethod(){ 49 personRepsotory.test(); 50 } 51 52 /** 53 * 目标: 实现带查询条件的分页. id > 5 的条件 54 * 55 * 调用 JpaSpecificationExecutor 的 Page<T> findAll(Specification<T> spec, Pageable pageable); 56 * Specification: 封装了 JPA Criteria 查询的查询条件 57 * Pageable: 封装了请求分页的信息: 例如 pageNo, pageSize, Sort 58 */ 59 //使用继承JpaSpecificationExecutor的方法实现条件查询+分页 60 @Test 61 public void testJpaSpecificationExecutor(){ 62 int pageNo = 3 - 1; 63 int pageSize = 5; 64 PageRequest pageable = new PageRequest(pageNo, pageSize); 65 66 //通常使用 Specification 的匿名内部类 67 Specification<Person> specification = new Specification<Person>() { 68 /** 69 * @param *root: 代表查询的实体类. 70 * @param query: 可以从中可到 Root 对象, 即告知 JPA Criteria 查询要查询哪一个实体类. 还可以 71 * 来添加查询条件, 还可以结合 EntityManager 对象得到最终查询的 TypedQuery 对象. 72 * @param *cb: CriteriaBuilder 对象. 用于创建 Criteria 相关对象的工厂. 当然可以从中获取到 Predicate 对象 73 * @return: *Predicate 类型, 代表一个查询条件. 74 */ 75 @Override 76 public Predicate toPredicate(Root<Person> root, 77 CriteriaQuery<?> query, CriteriaBuilder cb) { 78 Path path = root.get("id"); 79 Predicate predicate = cb.gt(path, 5); 80 return predicate; 81 } 82 }; 83 84 Page<Person> page = personRepsotory.findAll(specification, pageable); 85 86 System.out.println("总记录数: " + page.getTotalElements()); 87 System.out.println("当前第几页: " + (page.getNumber() + 1)); 88 System.out.println("总页数: " + page.getTotalPages()); 89 System.out.println("当前页面的 List: " + page.getContent()); 90 System.out.println("当前页面的记录数: " + page.getNumberOfElements()); 91 } 92 93 //使用继承JpaRepository的方法 94 @Test 95 public void testJpaRepository(){ 96 Person person = new Person(); 97 person.setBirth(new Date()); 98 person.setEmail("[email protected]"); 99 person.setLastName("xyz"); 100 person.setId(28); 101 102 Person person2 = personRepsotory.saveAndFlush(person); 103 104 System.out.println(person == person2); 105 } 106 107 //使用继承PagingAndSortingRespository的方法,实现分页 108 @Test 109 public void testPagingAndSortingRespository(){ 110 //pageNo 从 0 开始. 111 int pageNo = 6 - 1; 112 int pageSize = 5; 113 //Pageable 接口通常使用的其 PageRequest 实现类. 其中封装了需要分页的信息 114 //排序相关的. Sort 封装了排序的信息 115 //Order 是具体针对于某一个属性进行升序还是降序. 116 Order order1 = new Order(Direction.DESC, "id"); 117 Order order2 = new Order(Direction.ASC, "email"); 118 Sort sort = new Sort(order1, order2); 119 120 PageRequest pageable = new PageRequest(pageNo, pageSize, sort); 121 Page<Person> page = personRepsotory.findAll(pageable); 122 123 System.out.println("总记录数: " + page.getTotalElements()); 124 System.out.println("当前第几页: " + (page.getNumber() + 1)); 125 System.out.println("总页数: " + page.getTotalPages()); 126 System.out.println("当前页面的 List: " + page.getContent()); 127 System.out.println("当前页面的记录数: " + page.getNumberOfElements()); 128 } 129 130 //使用继承CrudReposiory的方法 131 @Test 132 public void testCrudReposiory(){ 133 List<Person> persons = new ArrayList<>(); 134 135 for(int i = ‘a‘; i <= ‘z‘; i++){ 136 Person person = new Person(); 137 person.setAddressId(i + 1); 138 person.setBirth(new Date()); 139 person.setEmail((char)i + "" + (char)i + "@atguigu.com"); 140 person.setLastName((char)i + "" + (char)i); 141 142 persons.add(person); 143 } 144 145 personService.savePersons(persons); 146 } 147 148 @Test 149 public void testModifying(){ 150 // personRepsotory.updatePersonEmail(1, "[email protected]"); 151 personService.updatePersonEmail("[email protected]", 1); 152 } 153 154 //设置 nativeQuery=true 即可以使用原生的 SQL 查询 155 @Test 156 public void testNativeQuery(){ 157 long count = personRepsotory.getTotalCount(); 158 System.out.println(count); 159 } 160 161 162 //使用 @Query 几种传递参数的方式 163 @Test 164 public void testQueryAnnotationLikeParam(){ 165 // List<Person> persons = personRepsotory.testQueryAnnotationLikeParam("%A%", "%bb%"); 166 // System.out.println(persons.size()); 167 168 // List<Person> persons = personRepsotory.testQueryAnnotationLikeParam("A", "bb"); 169 // System.out.println(persons.size()); 170 171 List<Person> persons = personRepsotory.testQueryAnnotationLikeParam2("bb", "A"); 172 System.out.println(persons.size()); 173 } 174 175 @Test 176 public void testQueryAnnotationParams2(){ 177 List<Person> persons = personRepsotory.testQueryAnnotationParams2("[email protected]", "AA"); 178 System.out.println(persons); 179 } 180 181 @Test 182 public void testQueryAnnotationParams1(){ 183 List<Person> persons = personRepsotory.testQueryAnnotationParams1("AA", "[email protected]"); 184 System.out.println(persons); 185 } 186 187 //使用 @Query 注解可以自定义 JPQL 语句以实现更灵活的查询 188 @Test 189 public void testQueryAnnotation(){ 190 Person person = personRepsotory.getMaxIdPerson(); 191 System.out.println(person); 192 } 193 194 //根据外键条件查询,注意下划线的使用,若无下滑线,将优先获取person的属性,下滑线则表示为外键 195 @Test 196 public void testKeyWords2(){ 197 List<Person> persons = personRepsotory.getByAddress_IdGreaterThan(1); 198 System.out.println(persons); 199 } 200 201 //几种条件查询的例子 202 @Test 203 public void testKeyWords(){ 204 List<Person> persons = personRepsotory.getByLastNameStartingWithAndIdLessThan("X", 10); 205 System.out.println(persons); 206 207 persons = personRepsotory.getByLastNameEndingWithAndIdLessThan("X", 10); 208 System.out.println(persons); 209 210 persons = personRepsotory.getByEmailInAndBirthLessThan(Arrays.asList("[email protected]", "[email protected]", 211 "[email protected]"), new Date()); 212 System.out.println(persons.size()); 213 } 214 215 //获取lastname为AA的person 216 @Test 217 public void testHelloWorldSpringData() throws FileNotFoundException, IOException, InstantiationException, IllegalAccessException{ 218 System.out.println(personRepsotory.getClass().getName()); 219 Person person = personRepsotory.getByLastName("AA"); 220 System.out.println(person); 221 } 222 223 //验证数据库连接是否成功 224 @Test 225 public void testDataSource() throws SQLException { 226 DataSource dataSource = ctx.getBean(DataSource.class); 227 System.out.println(dataSource.getConnection()); 228 } 229 230 }
持久层类:
1 package com.atguigu.springdata; 2 3 import java.util.Date; 4 import java.util.List; 5 6 import org.springframework.data.jpa.repository.JpaRepository; 7 import org.springframework.data.jpa.repository.JpaSpecificationExecutor; 8 import org.springframework.data.jpa.repository.Modifying; 9 import org.springframework.data.jpa.repository.Query; 10 import org.springframework.data.repository.query.Param; 11 12 /** 13 * 1. Repository 是一个空接口. 即是一个标记接口 14 * 2. 若我们定义的接口继承了 Repository, 则该接口会被 IOC 容器识别为一个 Repository Bean. 15 * 纳入到 IOC 容器中. 进而可以在该接口中定义满足一定规范的方法. 16 * 17 * 3. 实际上, 也可以通过 @RepositoryDefinition 注解来替代继承 Repository 接口 18 */ 19 /** 20 * 在 Repository 子接口中声明方法 21 * 1. 不是随便声明的. 而需要符合一定的规范 22 * 2. 查询方法以 find | read | get 开头 23 * 3. 涉及条件查询时,条件的属性用条件关键字连接 24 * 4. 要注意的是:条件属性以首字母大写。 25 * 5. 支持属性的级联查询. 若当前类有符合条件的属性, 则优先使用, 而不使用级联属性. 26 * 若需要使用级联属性, 则属性之间使用 _ 进行连接. 27 */ 28 //@RepositoryDefinition(domainClass=Person.class,idClass=Integer.class) 29 public interface PersonRepsotory extends 30 JpaRepository<Person, Integer>, 31 JpaSpecificationExecutor<Person>, PersonDao{ 32 33 //根据 lastName 来获取对应的 Person 34 Person getByLastName(String lastName); 35 36 //WHERE lastName LIKE ?% AND id < ? 37 List<Person> getByLastNameStartingWithAndIdLessThan(String lastName, Integer id); 38 39 //WHERE lastName LIKE %? AND id < ? 40 List<Person> getByLastNameEndingWithAndIdLessThan(String lastName, Integer id); 41 42 //WHERE email IN (?, ?, ?) OR birth < ? 43 List<Person> getByEmailInAndBirthLessThan(List<String> emails, Date birth); 44 45 //WHERE a.id > ? 46 List<Person> getByAddress_IdGreaterThan(Integer id); 47 48 //查询 id 值最大的那个 Person 49 //使用 @Query 注解可以自定义 JPQL 语句以实现更灵活的查询 50 @Query("SELECT p FROM Person p WHERE p.id = (SELECT max(p2.id) FROM Person p2)") 51 Person getMaxIdPerson(); 52 53 //为 @Query 注解传递参数的方式1: 使用占位符. 54 @Query("SELECT p FROM Person p WHERE p.lastName = ?1 AND p.email = ?2") 55 List<Person> testQueryAnnotationParams1(String lastName, String email); 56 57 //为 @Query 注解传递参数的方式1: 命名参数的方式. 58 @Query("SELECT p FROM Person p WHERE p.lastName = :lastName AND p.email = :email") 59 List<Person> testQueryAnnotationParams2(@Param("email") String email, @Param("lastName") String lastName); 60 61 //SpringData 允许在占位符上添加 %%. 62 @Query("SELECT p FROM Person p WHERE p.lastName LIKE %?1% OR p.email LIKE %?2%") 63 List<Person> testQueryAnnotationLikeParam(String lastName, String email); 64 65 //SpringData 允许在占位符上添加 %%. 66 @Query("SELECT p FROM Person p WHERE p.lastName LIKE %:lastName% OR p.email LIKE %:email%") 67 List<Person> testQueryAnnotationLikeParam2(@Param("email") String email, @Param("lastName") String lastName); 68 69 //设置 nativeQuery=true 即可以使用原生的 SQL 查询 70 @Query(value="SELECT count(id) FROM jpa_persons", nativeQuery=true) 71 long getTotalCount(); 72 73 //可以通过自定义的 JPQL 完成 UPDATE 和 DELETE 操作. 注意: JPQL 不支持使用 INSERT 74 //在 @Query 注解中编写 JPQL 语句, 但必须使用 @Modifying 进行修饰. 以通知 SpringData, 这是一个 UPDATE 或 DELETE 操作 75 //UPDATE 或 DELETE 操作需要使用事务, 此时需要定义 Service 层. 在 Service 层的方法上添加事务操作. 76 //默认情况下, SpringData 的每个方法上有事务, 但都是一个只读事务. 他们不能完成修改操作! 77 @Modifying 78 @Query("UPDATE Person p SET p.email = :email WHERE id = :id") 79 void updatePersonEmail(@Param("id") Integer id, @Param("email") String email); 80 } 81
自定义方法时,声明的接口:
1 package com.atguigu.springdata; 2 3 public interface PersonDao { 4 5 void test(); 6 7 }
其实现类:使用原生entityManager
1 package com.atguigu.springdata; 2 3 import javax.persistence.EntityManager; 4 import javax.persistence.PersistenceContext; 5 6 public class PersonRepsotoryImpl implements PersonDao { 7 8 @PersistenceContext 9 private EntityManager entityManager; 10 11 @Override 12 public void test() { 13 Person person = entityManager.find(Person.class, 11); 14 System.out.println("-->" + person); 15 } 16 17 }
PersonService:用于测试需要事务包裹的方法
1 package com.atguigu.springdata; 2 3 import java.util.List; 4 5 import org.springframework.beans.factory.annotation.Autowired; 6 import org.springframework.stereotype.Service; 7 import org.springframework.transaction.annotation.Transactional; 8 9 @Service 10 public class PersonService { 11 12 @Autowired 13 private PersonRepsotory personRepsotory; 14 15 @Transactional 16 public void savePersons(List<Person> persons){ 17 personRepsotory.save(persons); 18 } 19 20 @Transactional 21 public void updatePersonEmail(String email, Integer id){ 22 personRepsotory.updatePersonEmail(id, email); 23 } 24 }
与数据库表单对应的实体类:
1 package com.atguigu.springdata; 2 3 import java.util.Date; 4 5 import javax.persistence.Column; 6 import javax.persistence.Entity; 7 import javax.persistence.GeneratedValue; 8 import javax.persistence.Id; 9 import javax.persistence.JoinColumn; 10 import javax.persistence.ManyToOne; 11 import javax.persistence.Table; 12 13 @Table(name="JPA_PERSONS") 14 @Entity 15 public class Person { 16 17 private Integer id; 18 private String lastName; 19 20 private String email; 21 private Date birth; 22 23 private Address address; 24 25 private Integer addressId; 26 27 @GeneratedValue 28 @Id 29 public Integer getId() { 30 return id; 31 } 32 33 public void setId(Integer id) { 34 this.id = id; 35 } 36 37 public String getLastName() { 38 return lastName; 39 } 40 41 public void setLastName(String lastName) { 42 this.lastName = lastName; 43 } 44 45 public String getEmail() { 46 return email; 47 } 48 49 public void setEmail(String email) { 50 this.email = email; 51 } 52 53 public Date getBirth() { 54 return birth; 55 } 56 57 public void setBirth(Date birth) { 58 this.birth = birth; 59 } 60 61 @Column(name="ADD_ID") 62 public Integer getAddressId() { 63 return addressId; 64 } 65 66 public void setAddressId(Integer addressId) { 67 this.addressId = addressId; 68 } 69 70 @JoinColumn(name="ADDRESS_ID") 71 @ManyToOne 72 public Address getAddress() { 73 return address; 74 } 75 76 public void setAddress(Address address) { 77 this.address = address; 78 } 79 80 @Override 81 public String toString() { 82 return "Person [id=" + id + ", lastName=" + lastName + ", email=" 83 + email + ", brith=" + birth + "]"; 84 } 85 }
1 package com.atguigu.springdata; 2 3 import javax.persistence.Entity; 4 import javax.persistence.GeneratedValue; 5 import javax.persistence.Id; 6 import javax.persistence.Table; 7 8 @Table(name="JPA_ADDRESSES") 9 @Entity 10 public class Address { 11 12 private Integer id; 13 private String province; 14 private String city; 15 16 @GeneratedValue 17 @Id 18 public Integer getId() { 19 return id; 20 } 21 22 public void setId(Integer id) { 23 this.id = id; 24 } 25 26 public String getProvince() { 27 return province; 28 } 29 30 public void setProvince(String province) { 31 this.province = province; 32 } 33 34 public String getCity() { 35 return city; 36 } 37 38 public void setCity(String city) { 39 this.city = city; 40 } 41 42 }
使用的jar包:
项目结构:
补充:
以上是关于jpa+springdata的主要内容,如果未能解决你的问题,请参考以下文章