配置
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
application.properties
spring.jpa.properties.hibernate.hbm2ddl.auto=create-drop
對應表
@Entity
@Table(name = "user")
public class user {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
@Column(name="email")
private String email;
@Column(name="password")
private String password;
}
@Entity
註冊為 Spring bean@Table
對應資料表@Column
對應資料表中的欄位@Id
是資料表中的主鍵@GeneratedValue
自動生成
增刪改查
public interface UserRepository extends JpaRepository<User, Long>{
List<User> findAll();
List<User> findByEmail(String email);
}
JPA 以命名來規範各種 CRUD
– insert:save
– update:save
– delete:delete
– select:find
// SELECT...WHERE name = ?
findByName(String name);
// SELECT...WHERE name = ? AND age = ?
findByNameAndAge(String name, int age);
// SELECT...WHERE name LIKE ?
findByNameLike(String name);
// SELECT...WHERE age < ?
findByAgeLessThan(int age);
// SELECT...WHERE age <= ?
findByAgeLessThanEqual(int age);
// SELECT...WHERE age > ?
findByAgeGreaterThan(int age);
// SELECT...WHERE age > ?
findByAgeGreaterThanEqual(int age);
// SELECT...WHERE age < ? AND age > ?
findByAgeBetween(int age1, int age2);
Repository 做的是縱向篩選(WHERE)
對於橫向篩選(SELECT)
是拿到 Entity 後再去 get 出來
排序
// SELECT...WHERE name = ? ORDER BY age
findByNameOrderByAge(String name);
複合主鍵
如果是單一主鍵很單純,就是一個欄位
但如果是多個欄位組成的複合主鍵
在 JPA 該怎麼做呢?
需要新增一個額外的 PK 類別
@Embeddable
public class EnrollmentPk {
@Column
private String studentId;
@Column
private String courseCode;
}
Entity 則嵌入 PK 類別
@Entity
public class EnrollmentEntity {
@EmbeddedId
private EnrollmentPk pk;
@Column
private LocalDateTime registrationDate;
@Column
private LocalDateTime dropDate;
}
Repository 如果要搜尋的是複合主鍵中的欄位
命名為 findById + 欄位名稱
@Entity
public interface EnrollmentRepository extends JpaRepository<EnrollmentEntity, EnrollmentPk> {
public List<EnrollmentEntity> findByIdStudentId(String studentId);
public List<EnrollmentEntity> findByIdCourseCode(String courseCode);
}