【问题标题】:How to correctly use entitymanager for creating entity objects?如何正确使用 entitymanager 创建实体对象?
【发布时间】:2014-04-15 07:13:36
【问题描述】:

早安,

我目前正在进行我的第一个 JPA 项目,但在使用和理解实体管理器方面存在一些困难。我创建了几个类并通过注释将它们分配为实体。现在,我正在尝试创建一个类,它将通过 entityManager 创建一个实体对象。例如,我有以下课程:

@Entity
@Table(name = "product")
public class Product implements DefaultProduct {

@Id
@Column(name = "product_name", nullable = false)
private String productName;

@Column(name = "product_price", nullable = false)
private double productPrice;

@Column(name = "product_quantity", nullable = false)
private int productQuantity;

@ManyToOne
@JoinColumn(name = "Product_Account", nullable = false)
private Account parentAccount;

public Product(String productName, double productPrice,
        int productQuantity, Account parentAccount)
        throws IllegalArgumentException {

    if (productName == null || productPrice == 0 || productQuantity == 0) {
        throw new IllegalArgumentException(
                "Product name/price or quantity have not been specified.");
    }
    this.productName = productName;
    this.productPrice = productPrice;
    this.productQuantity = productQuantity;
    this.parentAccount = parentAccount;
}

public String getProductName() {
    return productName;
}

public double getPrice() {
    return productPrice * productQuantity;
}

public int getQuantity() {
    return productQuantity;
}

public Account getAccount() {
    return parentAccount;
}

}

现在,我正在尝试创建这个类:

public class CreateProduct {

private static final String PERSISTENCE_UNIT_NAME = "Product";

EntityManagerFactory factory = Persistence
        .createEntityManagerFactory(PERSISTENCE_UNIT_NAME);

public void createProduct(Product product) {
    EntityManager manager = factory.createEntityManager();
    manager.getTransaction().begin();

//code to be written here

    manager.getTransaction().commit();

}
}

您能否给我一个代码示例,我必须在 createProduct 方法中的 begin() 和 commit() 行之间写下这些代码;另外,如果您能解释 entitymanager 的工作原理,我将不胜感激。我已经阅读了几个关于此的文档,但我仍然需要一些澄清。

提前致谢

【问题讨论】:

    标签: java entity-framework jpa


    【解决方案1】:
     Account account - new Account();
     Product product = new Product("name", 10, 11, account);
     manager.persist(product);
    

    根据您何时将 @Column @OneToOne 等注释放在字段或 getter 上,entityManager 将使用这种方式从类中获取字段值。它使用反射来读取注释,并通过使用它知道表应该是什么样子。通过了解表结构,它只会在后台创建一个查询,并将其发送到数据库。基本上,当您创建实体管理器工厂时,就会对类进行分析,并且此操作通常非常耗时(取决于数据库结构)。要深入了解它的工作原理,请阅读有关反射的更多信息。如果你得到反思,你会发现它是多么简单。

    【讨论】:

    • 感谢您的回复马雷克。就我而言,帐户也是一个实体;如果我将在我的 createProduct() 方法中创建一个帐户实例,它会导致任何冲突吗?
    • 应该以与 Product(@Entity 等)相同的方式完成。 EM 非常聪明,可以处理这个 :) 记住将两个类都放在 persistence.xml 中
    • 干杯伙伴!这给了我一些关于发生了什么的解释:D
    猜你喜欢
    • 1970-01-01
    • 2019-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多