原文轉自(http://blog.csdn.net/linlinv3/article/details/46605719)html
spring-data-jpa 使用方法
java
什麼是spring-datamysql
爲了簡化程序與數據庫交互的代碼,spring提供了一個現成的dao層框架,spring家族提供的spring-data適用於關係型數據庫和nosql數據庫 ;spring
例如 Spring Data JPA, Spring Data Hadoop, Spring Data MongoDB ,Spring Data Solr 等;sql
具體的能夠參考官網:http://projects.spring.io/spring-data/;mongodb
他們的共同特色是給咱們提供了框架代碼,spring Data能自動建立實體dao的實現類和自定義查詢,再也不須要咱們本身去實現了。數據庫
api地址: http://jpa.coding.io/ 中文apache
http://docs.spring.io/spring-data/data-jpa/docs/current/reference/html/ 英文 api
什麼是jpa?數組
JPA全稱爲Java持久性API(Java Persistence API),JPA是Java EE 5標準之一,是一個ORM規範,由廠商來實現該規範,目前有hibernate、OpenJPA、TopLink、EclipseJPA等實現;
如何使用JPA?
爲咱們提供了增刪改查的接口:
1、查詢: 查詢的方法有不少,我不一一列舉,常常使用的在這裏列舉一下:
一、查詢全部數據 findAll()
二、分頁查詢 findAll(new PageRequest(0, 2))
三、根據id查詢 findOne()
四、根據實體類屬性查詢: findByProperty (type Property); 例如:findByAge(int age);
五、排序: findAll(sort )
Sort sort = new Sort(Sort.Direction.DESC, "age").and (new Sort(Sort.Direction.DESC, "id"));
六、條件查詢 and/or/findByAgeLessThan/LessThanEqual 等,
例如: findByUsernameAndPassword(String username , String password)
七、總數 查詢 count() 或者 根據某個屬性的值查詢總數countByAge(int age);
八、是否存在某個id exists()
2、修改,刪除,新增
新增:直接使用 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<String> userList) ,方法的參數能夠是 Collection 類型,也能夠是數組或者不定長參數;
NotIn => 等價於 SQL 中的 "not in",例如: findByUsernameNotIn(Collection<String> 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.0</modelVersion>
<groupId>org.springframework</groupId>
<artifactId>gs-accessing-data-jpa</artifactId>
<version>0.1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.4.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>https://repo.spring.io/libs-release</url>
</repository>
<repository>
<id>org.jboss.repository.releases</id>
<name>JBoss Maven Release Repository</name>
<url>https://repository.jboss.org/nexus/content/repositories/releases</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>https://repo.spring.io/libs-release</url>
</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<Customer, Long>{ // MongoRepository ===> CrudRepository
List<Customer> findByAge(int age);
List<Customer> findByAgeLessThan(int age);
List<Customer> findById(long id);
List<Customer> findByUsernameAndPassword(String username , String password);
List<Customer> findByUsernameOrPassword(String username , String password);
long countByAge(int age);
long deleteByAge(int age);
/* @Query("firstName:*?0* OR lastName:*?0*")
public List<Customer> 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<Customer> 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<Customer> 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);
}