Spring Data Jdbc 是否启用连接外键而不是 id ?



尝试了很多选项,但一直都有错误的联接。存储库不是通过填充在supplier_contracts表的'status'列中的id来获取实际的status_name,而是返回这两个表的联接id。那么,我如何通过状态列supplierContractRepository.findById(3L(的int检索status_name?

状态实体

CREATE TABLE `contract_statuses` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
);
public class ContractStatuses {

@Id
Integer id;
String name;
public ContractStatuses(int id, String name) {
this.id = id;
this.name = name;
}
} 

合同实体

CREATE TABLE `suppliers_contracts` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`supplier` bigint(20) NOT NULL,
`cabs_id` int(11) DEFAULT NULL,
`start_date` date DEFAULT NULL,
`end_date` date DEFAULT NULL,
`attorny_end_date` date DEFAULT NULL,
`number_of_payments` int(11) DEFAULT NULL,
`payment_amount` int(11) DEFAULT NULL,
`comments` varchar(2000) DEFAULT NULL,
`close_date` timestamp NULL DEFAULT NULL,
`status` int(11) NOT NULL,
`created_on` timestamp NOT NULL DEFAULT current_timestamp(),
PRIMARY KEY (`id`)
);
@Table("suppliers_contracts")
public class SupplierContract {
@Id
Long id;
Long supplier;
Long cabsId;
Date startDate;
Date endDate;
int paymentAmount;
Date attornyEndDate;
int numberOfPayments;
String comments;
Date closeDate;
@MappedCollection(idColumn = "id")
ContractStatuses status;

public SupplierContract(Long id, Long supplier, Long cabsId, Date startDate, Date endDate,Date attornyEndDate, int numberOfPayments, int paymentAmount,
String comments, Date closeDate,ContractStatuses status) {
this.id = id;
this.supplier = supplier;
this.cabsId = cabsId;
this.startDate = startDate;
this.endDate = endDate;
this.attornyEndDate = attornyEndDate;
this.numberOfPayments = numberOfPayments;
this.paymentAmount = paymentAmount;
this.comments = comments;
this.closeDate = closeDate;
this.status = status;
}
}
//Getters and setters here
@GetMapping("/getContracts")
public Optional<SupplierContract> getSupp(){
Optional<SupplierContract>  contract = supplierContractRepository.findById(3L);
return contract ;
}

您有多种选择:

  1. 默认变体是通过对单独ContractStatusRepository的单独调用加载状态。由于这些状态可能不会经常更改,因此您可能会考虑为此进行缓存。

  2. 如果您只想要状态而不关心合同,则可以向存储库添加一个带有@Query注释的附加方法,该方法使用SQL联接根据合同的id选择状态的两个字段。

  3. 此项仅适用于只读访问您可以创建另一个实体ReadOnlyContract,其中包含ContractStatuses引用,标记为嵌入属性。现在,您可以将其映射到包含其他状态字段的视图中。为了避免意外使用写入方法,您应该让存储库从Repository继承,并只添加您实际需要的读取方法。

应该使用SupplierContractContractStatuses类之间的DB关系。

即使用ContractStatuses contractStatuses;而不是int status;,然后使用关系一对多。当您查询findAll()时,您将从可以获得status_name的位置获得ContractStatuses

最新更新