JPA
JPA简介
首先介绍一下JPA,他是由SUN公司提出来的Java持久化规范,
它为Java开发人员提供了一种对象/关联映射工具来管理Java应用中的关系数据。他的出现主要是为了简化现有的持久化开发工作和整合ORM技术,结束现在Hibernate,TopLink,JDO等ORM框架各自为营的局面。值得注意的是,JPA是在充分吸收了现有Hibernate,TopLink,JDO等ORM框架的基础上发展而来的,具有易于使用,伸缩性强等优点。从目前的开发社区的反应上看,JPA受到了极大的支持和赞扬,其中就包括了Spring与EJB3.0的开发团队。
Spring data jpa
Spring Data JPA 是 Spring 基于 ORM 框架、JPA 规范的基础上封装的一套JPA应用框架,可使开发者用极简的代码即可实现对数据的访问和操作。它提供了包括增删改查等在内的常用功能,且易于扩展!学习并使用 Spring Data JPA 可以极大提高开发效率!
实例代码
首先我们建立一个SpringBoot的项目。在创建的时候记得勾选JPA,MySQL。
创建好的项目的POM.XML的依赖如下:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
然后下一步就是配置application.yml
server:
port: 8080
spring:
datasource:
url: jdbc:mysql://localhost:3306/girl
username: root
password:
driver-class-name: com.mysql.jdbc.Driver
jpa:
show-sql: true #是否显示数据库语句
hibernate:
ddl-auto: update #create:每一次启动都会创建新表,如果之前有的话就会先删掉
#update:每一次启动应用也会创建新表,如果有数据的时候就会保留表
#create-drop:功能与create类似,但是会在停止应用的时候删除表
#none:不做任何操作,默认
#validate:会自动验证表结构是否与类一致,不一致会报错。
上面完成一些基本的配置,现在我们便可以使用JPA了。JPA使用起来非常的方便,甚至都不需要你自己去建表,我们先把实体类写好,等下就能自动的帮我们创建数据表了。
Girl.java
package com.springboot.study.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity//实体类的注解
public class Girl {
@Id//标识这个字段为主键的注解
@GeneratedValue//属性自增的注解
private int id;
private int age;
private String cupSize;
public Girl(int id, int age, String cupSize) {
super();
this.id = id;
this.age = age;
this.cupSize = cupSize;
}
public Girl() {
super();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getCupSize() {
return cupSize;
}
public void setCupSize(String cupSize) {
this.cupSize = cupSize;
}
@Override
public String toString() {
return "Girl [id=" + id + ", age=" + age + ", cupSize=" + cupSize + "]";
}
}
现在我们只要将项目跑起来便能自动的生成数据表了。
那么怎样才能得到数据库的数据呢,其实非常的简单。
我们创建一个接口,然后继承JpaRepository就行了,这样就能使用JPA预先实现的增删改查了。
GirlRepository.java
package com.springboot.study.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import com.springboot.study.entity.Girl;
public interface GirlRepository extends JpaRepository<Girl,Integer>{
}
这样我们就能在获取到数据库的数据了,详情请看下面的Controller。
GirlController.java
package com.springboot.study.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.springboot.study.entity.Girl;
import com.springboot.study.repository.GirlRepository;
@RestController
public class GirlContrller {
@Autowired
GirlRepository girl;
@RequestMapping("/girls")//得到所有的Gilr数据
public List<Girl> getAllGirls(){
return girl.findAll();
}
@RequestMapping("/addGirl")//添加一个Girl数据
public Girl addGirl(Integer age,String cupSize){
Girl g=new Girl(0,age,cupSize);
return girl.save(g);
}
@RequestMapping("/findGirlById")//根据id查询一个Girl
public Girl findOneGirl(Integer id){
return girl.findOne(id);
}
@RequestMapping("/deleteGirlById")//根据ID删除一个Girl
public void deleteGirlById(Integer id){
girl.delete(id);
}
@RequestMapping("/uptGirl")//更新一个Girl
public Girl uptGirl(Integer id,Integer age,String cupSize){
Girl g=girl.save(new Girl(id,age,cupSize));
return g;
}
}
如果你觉得JPA默认实现的功能不符合你的要求的话,JPA的自定义扩展也是很方便的。比如我扩展一个按照cupSize查询的方法,就只要在就口中按照一定的规则添加一个方法就能够实现了,他会根据查询的方法去自动解析成SQL。
自定义简单查询
这种方式就是通过解析方法名来自动生成SQL,主要的语法是
findXXBy
,
readAXXBy
,
queryXXBy
,
countXXBy
,
getXXBy
后面跟属性名称:
List<Girl> findByCupSize(String cupSize);
也可以使用一些关键字如And、Or
List<Girl> findByAgeAndCupSize(Integer age,String cupSize);
修改、删除、统计也有相似的语法
Long deleteById(Long id);
Long countByUserName(String userName);
基本上SQL体系中的关键词都可以使用,例如:LIKE
、 IgnoreCase
、 OrderBy
。
List<User> findByEmailLike(String email);
User findByUserNameIgnoreCase(String userName);
List<User> findByUserNameOrderByEmailDesc(String email);
具体的关键字,使用方法和生产成SQL如下表所示
Keyword | Sample | JPQL snippet |
---|---|---|
And | findByLastnameAndFirstname | … where x.lastname = ?1 and x.firstname = ?2 |
Or | findByLastnameOrFirstname | … where x.lastname = ?1 or x.firstname = ?2 |
Is,Equals | findByFirstnameIs,findByFirstnameEquals | … where x.firstname = ?1 |
Between | findByStartDateBetween | … where x.startDate between ?1 and ?2 |
LessThan | findByAgeLessThan | … where x.age < ?1 |
LessThanEqual | findByAgeLessThanEqual | … where x.age ⇐ ?1 |
GreaterThan | findByAgeGreaterThan | … where x.age > ?1 |
GreaterThanEqual | findByAgeGreaterThanEqual | … where x.age >= ?1 |
After | findByStartDateAfter | … where x.startDate > ?1 |
Before | findByStartDateBefore | … where x.startDate < ?1 |
IsNull | findByAgeIsNull | … where x.age is null |
IsNotNull,NotNull | findByAge(Is)NotNull | … where x.age not null |
Like | findByFirstnameLike | … where x.firstname like ?1 |
NotLike | findByFirstnameNotLike | … where x.firstname not like ?1 |
StartingWith | findByFirstnameStartingWith | … where x.firstname like ?1 (parameter bound with appended %) |
EndingWith | findByFirstnameEndingWith | … where x.firstname like ?1 (parameter bound with prepended %) |
Containing | findByFirstnameContaining | … where x.firstname like ?1 (parameter bound wrapped in %) |
OrderBy | findByAgeOrderByLastnameDesc | … where x.age = ?1 order by x.lastname desc |
Not | findByLastnameNot | … where x.lastname <> ?1 |
In | findByAgeIn(Collection ages) | … where x.age in ?1 |
NotIn | findByAgeNotIn(Collection age) | … where x.age not in ?1 |
TRUE | findByActiveTrue() | … where x.active = true |
FALSE | findByActiveFalse() | … where x.active = false |
IgnoreCase | findByFirstnameIgnoreCase | … where UPPER(x.firstame) = UPPER(?1) |
分页查询
分页查询在实际使用中非常普遍了,spring data jpa已经帮我们实现了分页的功能,在查询的方法中,需要传入参数Pageable
,当查询中有多个参数的时候Pageable
建议做为最后一个参数传入
Page<User> findALL(Pageable pageable);
Page<User> findByUserName(String userName,Pageable pageable);
Pageable
是spring封装的分页实现类,使用的时候需要传入页数、每页条数和排序规则
@Test
public void testPageQuery() throws Exception {
int page=1,size=10;
Sort sort = new Sort(Direction.DESC, "id");
Pageable pageable = new PageRequest(page, size, sort);
userRepository.findALL(pageable);
userRepository.findByUserName("testName", pageable);
}
限制查询
有时候我们只需要查询前N个元素,或者支取前一个实体。
ser findFirstByOrderByLastnameAsc();
User findTopByOrderByAgeDesc();
Page<User> queryFirst10ByLastname(String lastname, Pageable pageable);
List<User> findFirst10ByLastname(String lastname, Sort sort);
List<User> findTop10ByLastname(String lastname, Pageable pageable);
自定义SQL查询
其实Spring data 觉大部分的SQL都可以根据方法名定义的方式来实现,但是由于某些原因我们想使用自定义的SQL来查询,spring data也是完美支持的;在SQL的查询方法上面使用@Query
注解,如涉及到删除和修改在需要加上@Modifying
.也可以根据需要添加 @Transactional
对事物的支持,查询超时的设置等
@Modifying
@Query("update User u set u.userName = ?1 where u.id = ?2")
int modifyByIdAndUserId(String userName, Long id);
@Transactional
@Modifying
@Query("delete from User where id = ?1")
void deleteByUserId(Long id);
@Transactional(timeout = 10)
@Query("select u from User u where u.emailAddress = ?1")
User findByEmailAddress(String emailAddress);
多表查询
多表查询在spring data jpa中有两种实现方式,第一种是利用hibernate的级联查询来实现,第二种是创建一个结果集的接口来接收连表查询后的结果,这里主要第二种方式。
首先需要定义一个结果集的接口类。
public interface HotelSummary {
City getCity();
String getName();
Double getAverageRating();
default Integer getAverageRatingRounded() {
return getAverageRating() == null ? null : (int) Math.round(getAverageRating());
}
}
查询的方法返回类型设置为新创建的接口
@Query("select h.city as city, h.name as name, avg(r.rating) as averageRating "
- "from Hotel h left outer join h.reviews r where h.city = ?1 group by h")
Page<HotelSummary> findByCity(City city, Pageable pageable);
@Query("select h.name as name, avg(r.rating) as averageRating "
- "from Hotel h left outer join h.reviews r group by h")
Page<HotelSummary> findByCity(Pageable pageable);
使用
Page<HotelSummary> hotels = this.hotelRepository.findByCity(new PageRequest(0, 10, Direction.ASC, "name"));
for(HotelSummary summay:hotels){
System.out.println("Name" +summay.getName());
}
对于Spring data JPA的总结就是以上了。在运行中Spring会给接口(HotelSummary)自动生产一个代理类来接收返回的结果,代码汇总使用
getXX
的形式来获取