簡體   English   中英

JPA-如何在不構造父對象的情況下構造ManyToOne關系的子對象

[英]JPA - How to construct child objects of a ManyToOne relation without constructing the parent object

每次我在DAO中編寫“創建”方法時,都必須在對象已經存在且僅具有ID的情況下使用注釋@ManyToOne構造對象。 如以下示例所示。

我有班級Employee:

@Entity  
public class Employee  
{  
    @Id
    private Long id;  

    private String employeeName;  

    @ManyToOne
    private Employer employer;  

    ...

}

在DAO中,我有一種使用現有雇主的ID創建雇員的方法。 這是我通常解決的方法:

public class EmployeeDAO {

    ...


    public void createEmployee(String name, String employerId) {

        Employee employee = new Employee();
        employee.setName(name);

        Employer employer = new Employer();
        employer.setId(employerId);
        employee.setEmployer(employer);

        save(employee);
    }

    ...
}

我想知道是否有一種更優雅的方式可以做到這一點,而無需創建“ new Employer()”

使用您的代碼,如果您的雇主已經在持久性上下文中加載,則可以獲取NonUniqueObjectException

最好的方法是加載雇主的代理人。 您可以使用:

// for hibernate session
Employer employer = session.load(Employer.class, employerId);

// EntityManager
Employer employer = entityManager.getReference(Employer.class, employerId);

或如果您使用Spring Data,請使用JpaRepository#getOne方法。

您可以閱讀此問題以獲取更多說明。

暫無
暫無

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

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