如何解决Spring Data Jdbc是否启用联接外键而不是ID?
尝试了很多选择,但一直以来我都错加入了。资源库不会通过填充在vendor_contracts表的“状态”列中的ID来获取实际的status_name,而是会返回2个表的联接ID。那么我该如何通过status列supplierProviderContractRepository.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 ;
}
解决方法
您有多种选择:
-
默认变体是通过对单独的
ContractStatusRepository
的单独调用来加载状态。由于这些状态可能不会经常更改,因此您可以考虑为此进行缓存。 -
如果您只想了解状态,而不关心合同,则可以使用
@Query
批注向存储库添加其他方法,该批注根据{{ 1}}使用SQL连接的合同。 -
这仅适用于只读访问权限! 您可以创建另一个实体
id
,其中包含ReadOnlyContract
引用,标记为嵌入式属性。现在,您可以将其映射到包含其他状态字段的视图。 为了避免意外使用写入方法,您应该使存储库继承自ContractStatuses
,并仅添加实际需要的读取方法。
您应该在SupplierContract
和ContractStatuses
类之间使用数据库关系。
例如,使用ContractStatuses contractStatuses;
而不是int status;
,然后在查询findAll()
时使用一对多关系,您将从获得{{ 1}}。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。