jpa(springdate-jpa)簡單應用 JPA 基礎(一)
阿新 • • 發佈:2018-11-28
原創部落格地址:https://blog.csdn.net/cheidou123/article/details/84428092
JPA 基礎(一)
JPA全稱Java Persistence API,是一組用於將資料存入資料庫的類和方法的集合。
一、JPA的基本配置
1 jpa配置
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
package com.example.demo.dto;
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 String firstName;
private String lastName;
protected Customer() {}
public Customer(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
@Override
public String toString() {
return String.format(
"Customer[id=%d, firstName='%s', lastName='%s']",
id, firstName, lastName);
}
}
package com.example.demo.repositories;
import com.example.demo.dto.Customer;
import org.springframework.data.jpa.repository.JpaRepository;
public interface CustomerRepository extends JpaRepository<Customer, Long>; {
}
二、JpaRepository
JpaRepository
PagingAndSortingRepository
CrudRepository
QueryByExampleExecutor
三、自定義的方法
1.一些基本的自定義方法樣例
2.舉個例子
在CustomerRepository介面中,有如下定義
/**
* 根據lastName查詢結果
* @param lastName
* @return
*/
List<Customer> findByLastName(String lastName);