【问题标题】:Saving entity using prorotype of objects in properties使用属性中的对象原型保存实体
【发布时间】:2016-09-01 20:21:03
【问题描述】:

我正在使用 JPA 并拥有下一个实体

@Entity
public class Employee {
    @Id
    int id;
    String name;

    @ManyToOne
    Employee manager;

    @OneToMany(mappedBy="manager",fetch=FetchType.EAGER)
    Set<Employee> subordinaries;

 // constructors , getters, setters 
}

我可以使用属性对象的原型来保存吗?这是有效的,但我不确定这是一个好习惯。这是 DAO 类:

public class CompanyOrm {

    @PersistenceContext(unitName="springHibernate")
    EntityManager em;

    ...

    @Transactional
    public void addEmployee(int id, String name, int managerId){

        //Using prototype of object manager - not 
        //object retrived from database with 
        //em.find(Employee.class, managerId)
        //where filled only id

        Employee prototype = new Employee();
        prototype.setId(managerId);
        Employee e = new Employee(id, name, prototype);
        em.persist(e);
    }

   ...
}

【问题讨论】:

    标签: java jpa orm persistence entities


    【解决方案1】:

    它可能有效,但容易出错,因为原型实例不受管理。

    您应该使用em.getReference(Employee.class, managerId) 创建被引用的实体。它在实体上返回一个未初始化的代理,而不去数据库。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多