【发布时间】: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