簡體   English   中英

Hibernate,如果擁有的實體相同,則使用已保存在數據庫中的實體與擁有方鏈接,而不是創建新實體

[英]Hibernate, use the entity already persisted in DB to link with owning side instead of creating a new one if the owned entity is same

I am new to the hibernate, I have a spring boot project using hibernate and spring data jpa.

我有一個實體TestCase,它有一個InputJSON,不同的TestCase 可以有相同的InputJSON。 下面是片段

測試用例.java

@Id
@GeneratedValue(generator = "sequence-generator")
@SequenceGenerator(name = "sequence-generator", initialValue = 1, 
sequenceName = "test_case_id_sequence ", allocationSize = 50)
private long testCaseId;

private String name;

@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "input_JSON_ID")
private InputJSON inputJSON;
...

輸入JSON.java

@Id
@GeneratedValue(generator = "sequence-generator")
@SequenceGenerator(name = "sequence-generator", allocationSize = 50, 
sequenceName ="input_JSON_ID_Sequence",initialValue = 1)
private long inputJSONId;

private String json;
private String header;

@OneToMany(cascade = CascadeType.ALL, mappedBy = "inputJSON")
private List<TestCase> testCase;

我在兩個實體中都覆蓋了 equals() 和 hashcode()。 當我按以下方式堅持時,它工作正常並且休眠將我的測試用例與相同的 inputJson 鏈接起來。

InputJSON json1=new InputJSON();
json1.setHeader("header");
json1.setJson("json");

TestCase tc1=new TestCase();
tc1.setName("test1");
tc1.setInputJSON(json1);

TestCase tc2=new TestCase();
tc2.setName("test2");
tc2.setInputJSON(json1);

repository.save(tc1);
repository.save(tc2);

但是當我這樣堅持時,hibernate 正在為 InputJSON 創建兩行。

InputJSON json1=new InputJSON();
json1.setHeader("header");
json1.setJson("json");

InputJSON json2=new InputJSON();
json2.setHeader("header");
json2.setJson("json");

TestCase tc1=new TestCase();
tc1.setName("test1");
tc1.setInputJSON(json1);

TestCase tc2=new TestCase();
tc2.setName("test2");
tc2.setInputJSON(json2);

repository.save(tc1);
repository.save(tc2);

更新:

我正在接收測試用例並在 DTO 中輸入 json 信息,問題是我為不同的測試用例接收不同的 DTO,我必須從中創建合理的模型。所以要知道兩個 json 是相等的,我必須先以編程方式比較它們堅持在我想避免的數據庫中(如果可以避免的話)並讓 hibernate 處理它們。

輸入DTO.java

private String testCaseDescription;
private boolean skipTest;
private String params;
private String headerJson;
private String inputJson;

其中 repository 是我的 JPARepository 的自動連接實例。

如果 JSONS 相同,hibernate 中是否有一種方法或解決方法可以只創建一行,我已經嘗試了一些事情,我知道我可以從數據庫中獲取 JSONS 並將它們與我的新 json 進行比較,如果它們相同,則已經持久化一個而不是創建一個新的,我還對 hibernate 對等號和哈希碼的使用進行了一些挖掘,我發現休眠只在 Set 中使用它們。

你需要扭轉局面。

您需要設置testCase列表,然后保存json1 object

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM