Spring Data JPA Query Method可以透過定義方法名稱來作為查詢的條件。當查詢或排序條件為@EmbeddedId
複合主鍵(compound key)中的屬性時的命名方式如下。
例如EMPLOYEE
資料表的主鍵為由本身的EMPLOYEE_ID
及外鍵REGION_ID
,DEPARTMENT_ID
組成,則JPA的entiy類Employee
設計如下。
Employee
@Entity
@Table(name="EMPLOYEE")
public class Employee {
@EmbeddedId
private EmployeePk id;
private String name;
private int age;
// getter and setter ommitted
}
EMPLOYEE
的複合主鍵使用@EmbeddedId
及一個@Embeddable
類別EmployeePk
來設定。
@Embeddable
public class EmployeePk implements Serializable {
private long employeeId;
private long departmentId;
private long regionId;
// getter and setter ommitted
}
在EmployeeRepository
定義方法名稱時若查詢或排序條件包含了EmployeePk
中的欄位,則命名方式如下。
public interface EmployeeRepository extends JpaRepository<Employee, EmployeePk> {
/**
* from
* EMPLOYEE
* where
* EMPLOYEE_ID = ?
* and DEPARTMENT_ID = ?
* and REGION_ID = ?
*/
List<Employee> findByIdAndAge(EmployeePk id, int age);
/**
* from
* EMPLOYEE
* where
* EMPLOYEE_ID = ?
* and NAME = ?
* order by
* DEPARTMENT_ID asc
*/
List<Employee> findByIdEmployeeIdAndNameOrderByIdDepartmentId(long employeeId, String name);
/**
* from
* EMPLOYEE
* where
* REGION_ID = ?
* AGE = ?
* order by
* REGION_ID asc,
* DEPARTMENT_ID asc,
* AGE desc
*/
List<Employee> findByIdRegionIdAndAgeOrderByIdRegionIdAscIdDepartmentIdAscAgeDesc(long regionId, int age);
}
沒有留言:
張貼留言