spring-data-jpa 使用方法
什么是spring-data
为了简化程序与数据库交互的代码,spring提供了一个现成的dao层框架,spring家族提供的spring-data适用于关系型数据库和nosql数据库 ;
例如 Spring Data JPA, Spring Data Hadoop, Spring Data MongoDB ,Spring Data Solr 等;
具体的可以参考官网:http://projects.spring.io/spring-data/;
他们的共同特点是给我们提供了框架代码,spring Data能自动创建实体dao的实现类和自定义查询,不再需要我们自己去实现了。
api地址: http://jpa.coding.io/ 中文
http://docs.spring.io/spring-data/data-jpa/docs/current/reference/html/ 英文
什么是jpa?
JPA全称为Java持久性API(Java Persistence API),JPA是Java EE 5标准之一,是一个ORM规范,由厂商来实现该规范,目前有Hibernate、OpenJPA、TopLink、EclipseJPA等实现;
如何使用JPA?
为我们提供了增删改查的接口:
一、查询: 查询的方法有很多,我不一一列举,经常使用的在这里列举一下:
1、查询所有数据 findAll()
2、分页查询 findAll(new PageRequest(0, 2))
3、根据id查询 findOne()
4、根据实体类属性查询: findByProperty (type Property); 例如:findByAge(int age);
5、排序: findAll(sort )
Sort sort = new Sort(Sort.Direction.DESC, "age").and (new Sort(Sort.Direction.DESC, "id"));
6、条件查询 and/or/findByAgeLessThan/LessThanEqual 等,
例如: findByUsernameAndPassword(String username , String password)
7、总数 查询 count() 或者 根据某个属性的值查询总数countByAge(int age);
8、是否存在某个id exists()
二、修改,删除,新增
新增:直接使用 save(T) 方法
删除: delete() 或者 deleteByProperty 例如:deleteByAge(int age) ;
更新:@Modifying
@Query("update Customer u set u.age = ?1 where u.id = ?2")
int update(int age1 , long id);
官网上写出了所有的方法,非常详细,这里稍作列举
And => 等价于 SQL 中的 and 关键字 例如:findByUsernameAndPassword(String user, Striang pwd);
Or => 等价于 SQL 中的 or 关键字,例如:findByUsernameOrAddress(String user, String addr);
Between => 等价于 SQL 中的 between 关键字,例如:SalaryBetween(int max, int min);
LessThan => 等价于 SQL 中的 "<",例如: findBySalaryLessThan(int max);
GreaterThan => 等价于 SQL 中的">",例如: findBySalaryGreaterThan(int min);
IsNull => 等价于 SQL 中的 "is null",例如: findByUsernameIsNull();
IsNotNull => 等价于 SQL 中的 "is not null",例如: findByUsernameIsNotNull();
NotNull=> 与 IsNotNull 等价;
Like => 等价于 SQL 中的 "like",例如: findByUsernameLike(String user);
NotLike => 等价于 SQL 中的 "not like",例如: findByUsernameNotLike(String user);
OrderBy => 等价于 SQL 中的 "order by",例如: findByUsernameOrderBySalaryAsc(String user);
Not => 等价于 SQL 中的 "! =",例如: findByUsernameNot(String user);
In => 等价于 SQL 中的 "in",例如: findByUsernameIn(Collection userList) ,方法的参数可以是 Collection 类型,也可以是数组或者不定长参数;
NotIn => 等价于 SQL 中的 "not in",例如: findByUsernameNotIn(Collection userList) ,方法的参数可以是 Collection 类型,也可以是数组或者不定长参数;
创建一个按单字段排序的Sort对象: new Sort(Sort.Direction.DESC, "description").and(new Sort(Sort.Direction.ASC, "id"))
自己根据官网的demo稍作修改整理,
如下:
使用maven:
pom.xml如下:
xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0modelVersion>
<groupId>org.springframeworkgroupId>
<artifactId>gs-accessing-data-jpaartifactId>
<version>0.1.0version>
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>1.2.4.RELEASEversion>
parent>
<properties>
<java.version>1.8java.version>
properties>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-jpaartifactId>
dependency>
<dependency>
<groupId>com.h2databasegroupId>
<artifactId>h2artifactId>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
plugin>
plugins>
build>
<repositories>
<repository>
<id>spring-releasesid>
<name>Spring Releasesname>
<url>https://repo.spring.io/libs-releaseurl>
repository>
<repository>
<id>org.jboss.repository.releasesid>
<name>JBoss Maven Release Repositoryname>
<url>https://repository.jboss.org/nexus/content/repositories/releasesurl>
repository>
repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-releasesid>
<name>Spring Releasesname>
<url>https://repo.spring.io/libs-releaseurl>
pluginRepository>
pluginRepositories>
project>
目录结构如下:
代码部分:
Application.java
package hello;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
@SpringBootApplication
public class Application implements CommandLineRunner {
@Autowired
CustomerRepository repository;
public static void main(String[] args) {
SpringApplication.run(Application.class);
}
public void run(String... strings) throws Exception {
// save a couple of customers
repository.save(new Customer(12, "Jack","111111"));
repository.save(new Customer(12, "lucy","212111"));
repository.save(new Customer(24, "Kim", "2111111"));
repository.save(new Customer(22, "David", "2132111"));
repository.save(new Customer(32, "Michelle", "2343333"));
System.out.println("*******查询所有***********");
// fetch all customers
for (Customer customer : repository.findAll()) {
System.out.println(customer);
}
System.out.println("*******分页查询**********");
for (Customer customer : repository.findAll(new PageRequest(0, 2))) {
System.out.println(customer);
}
System.out.println("******根据id查询*****");
Customer customer1 = repository.findOne(1L);
System.out.println(customer1);
System.out.println("******根据属性查询*****");
for (Customer bauer : repository.findByAge(12)) {
System.out.println(bauer);
}
System.out.println("*******排序查询**********");
Sort sort = new Sort(Sort.Direction.DESC, "age").and (new Sort(Sort.Direction.DESC, "id"));
for(Customer customer : repository.findAll(sort)) {
System.out.println(customer);
}
System.out.println("********条件查询******");
for (Customer bauer : repository.findByAgeLessThan(27)) {
System.out.println(bauer);
}
for (Customer bauer : repository.findByUsernameAndPassword("Jack", "111111")) {
System.out.println(bauer);
}
for (Customer bauer : repository.findByUsernameOrPassword("Jack", "212111")) {
System.out.println(bauer);
}
System.out.println("*********count查询*********");
long count = repository.count(); //
System.out.println(count);
long countAge = repository.countByAge(12);
System.out.println(countAge);
System.out.println("****************判断是否存在*******************");
Boolean booelan = repository.exists(7L);
System.out.println(booelan);
System.out.println("**************************query **************************************");
System.out.println(repository.findByName("Jack"));
System.out.println(repository.findByName1("Jack"));
System.out.println(repository.findByName3("Jack"));
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
System.out.println("*******删除***********");
repository.delete(5L);
long deleteAge = repository.deleteByAge(32);
System.out.println(deleteAge);
System.out.println(repository.findByNamelike("ac"));
// System.out.println(repository.findByNamelike1("ac"));
System.out.println(repository.update(28,1L));
}
}
Customer.java
package hello;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Customer {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private long id;
private int age;
private String username;
private String password;
protected Customer() {}
public Customer(int age,String username,String password ) {
this.age = age;
this.username = username;
this.password = password;
}
@Override
public String toString() {
return String.format(
"Customer[id=%d, age='%d',username='%s',password='%s']",
id, age ,username,password);
}
}
CustomerRepository.java
package hello;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
public interface CustomerRepository extends JpaRepository{ // MongoRepository ===> CrudRepository
List findByAge(int age);
List findByAgeLessThan(int age);
List findById(long id);
List findByUsernameAndPassword(String username , String password);
List findByUsernameOrPassword(String username , String password);
long countByAge(int age);
long deleteByAge(int age);
/* @Query("firstName:*?0* OR lastName:*?0*")
public List findByQuery(String searchTerm, Sort sort);*/
@Query("select c from Customer c where c.username = ?1")
Customer findByName(String name);
@Query(value = "SELECT * FROM Customer WHERE username = ?1", nativeQuery = true)
Customer findByName1(String name);
@Query("from Customer where username =:username ")
List findByName3(@Param("username")String name);
@Query("select c from Customer c where c.username like %?1")
Customer findByNamelike(String name);
//@Query("from Customer where username like:%username% ")
//List findByNamelike1(@Param("username")String name);
@Query("update Customer c set c.username=?1 where c.username = ?2")
Customer updateByName(String name1,String name2);
@Modifying
@Query("update Customer u set u.age = ?1 where u.id = ?2")
int update(int age1 , long id);
}