创建具有一对一关系的查询

时间:2018-10-09 11:32:30

标签: spring-data-jpa

我有两个表...一个贷款表和一个客户表。客户可以提供多笔贷款,但我想一次将客户限制为一笔有效贷款。在第一笔贷款完成之前,他们无法创建第二笔贷款( loan.active = false

我已经这样设置了我的贷款表:

@Entity
public class Loan implements Serializable {

private static final long serialVersionUID = 0x62B6DA99AA12AAA8L;

@Column @GeneratedValue(strategy = GenerationType.AUTO) @Id private Integer id;

@OneToOne(fetch = FetchType.LAZY)
private Customer customer;

@Column private String dateLoaned;
@Column private String dateToReturn;
@Column private String dateOfReturn;
@Column private Boolean active=false;

客户表如下:

@Entity
public class Customer implements Serializable {

private static final long serialVersionUID = 0x63A6DA99BC12A8A8L;

@Column @GeneratedValue(strategy = GenerationType.AUTO) @Id private Integer id;
@Column private String firstname;
@Column private String surname;
@Column private String address;
@Column private String town;
@Column private String postcode;
@Column (unique=true) private String personalnumber;
@Column (unique=true) private String emailaddress;


@OneToOne(fetch = FetchType.EAGER)
private Loan loan;

这使我可以与同一位客户创建新的贷款。到目前为止一切顺利。

我想进行查询,以查询客户是否已经有一笔有效的贷款。

到目前为止,我的贷款库是:

@Query("select loan_id from Loan l where l.customer.id = :customerId and l.active = true")
Boolean customerHasActiveLoan(@Param("customerId") Integer customerId);

这是正确的方法吗?

1 个答案:

答案 0 :(得分:1)

Selected format is: <AVCaptureDeviceFormat: 0x282d58d00 'vide'/'420v' 1280x 720, { 3- 60 fps}, HRSI:4096x2304, fov:58.632, supports vis, max zoom:120.00 (upscales @2.91), AF System:2, ISO:23.0-736.0, SS:0.000013-0.333333> 2018-10-10 14:47:35.009890+0200 SampleApp[6799:1110910] [SceneKit] Error: Could not get pixel buffer (CVPixelBufferRef) Format after 3 seconds is: <AVCaptureDeviceFormat: 0x282d58fb0 'vide'/'420v' 1920x1080, { 3- 30 fps}, HRSI:4096x2304, fov:58.632, supports vis, max zoom:16.00 (upscales @1.94), AF System:2, ISO:23.0-736.0, SS:0.000013-0.333333> 中,您都可以拥有spring-data-jpa或编写一种生成查询的方法。拥有@Query并没有错,但是因为您的存储库方法非常简单,所以您也可以仅使用方法名

对于该示例,等效于:

@Query

可以简化为

//Will return the active loan, if exists, or null
@Query("select l from Loan l where l.customer.id = :customerId and l.active = true")
public Loan getActiveLoad(@Param("customerId") Integer customerId)

有时public Local findOneByCustomerIdAndActiveIsTrue(Long id) 方法可以生成长方法名称,因此,如果您愿意,可以使用method name注释