英文:
Self referencing OneToOne with custom where condition
问题
有没有一种方法可以通过使用自定义的选择和条件语句来进行实体的自引用?
假设我有这个实体:
@Entity
public class Contract {
@Id
private Long id;
private String name;
@OneToOne
private Contract selfContract;
}
对于 selfContract
,我需要创建一个选择语句,其中包含多个(稍微复杂的)条件,以根据 contract
实体本身的字段来获取正确的实体。在这个示例中,字段 name
将是一个条件。
我在考虑将 selfContract
链接到数据访问对象(DAO)类中的选择语句,该语句在我需要 selfContract
(惰性加载)时执行。但实际上我不确定这是否可行。
英文:
Is there a way to self reference an Entity by using a custom select and where condition?
Lets assume I have this Entity:
@Entity
public class Contract {
@Id
private Long id;
private String name;
@OneToOne
private Contract selfContract;
}
For the selfContract
I need to create a select with multiple (little complex) where conditions to get the right entity based in fields of the contract
Entity itself. In this example the field name
would be one where condition.
I was thinking to link the selfContract
to a select statement in the dao class which executes as soon I need the selfContract
(lazy). But actually not sure if this is even possible.
答案1
得分: 1
在这种情况下,您将在“外部”合同上进行选择,其中名称=“某个名称”,然后您可以从结果中获取selfContract。
如果您想要对其进行性能优化,您可以创建一个DTO进行选择。
然后,您可以直接选择selfContract,其中外部合同的名称=“某个名称”。
示例:
@Query("SELECT new ContractDTO(c.selfContract.id, c.selfContract.name) FROM Contract c WHERE c.name = :name")
List<ContractDTO> retrieveSelfContractsByContractNameAsDTO(@Param("name") String name);
英文:
In this case you would make a select on the "outer" contract where name = "some name" and then you can get the selfContract from the result.
In case you want to performance optimize it a bit then you can make a dto you select to.
Then you can select the selfContract directly where the outer contracts name = "some name"
example:
@Query("SELECT new ContractDTO(c.selfContract.id, c.selfContract.name) FROM Contract c WHERE c.name = :name")
List<ContractDTO> retrieveSelfContractsByContractNameAsDTO(@Param("name") String name);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论