Java 如何正确使用entitymanager创建实体对象?

Java 如何正确使用entitymanager创建实体对象?,java,entity-framework,jpa,Java,Entity Framework,Jpa,你好 我目前正在进行我的第一个JPA项目,我在使用和理解EntityManager方面有一些困难。我创建了几个类,并通过注释将它们指定为实体。现在,我正在尝试创建一个类,该类将通过entityManager创建实体对象。例如,我有以下类: @Entity @Table(name = "product") public class Product implements DefaultProduct { @Id @Column(name = "product_name", nullable = f

你好

我目前正在进行我的第一个JPA项目,我在使用和理解EntityManager方面有一些困难。我创建了几个类,并通过注释将它们指定为实体。现在,我正在尝试创建一个类,该类将通过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是如何工作的,我将不胜感激。我已经阅读了一些关于这方面的文件,但我仍然需要一些澄清

提前谢谢

 Account account - new Account();
 Product product = new Product("name", 10, 11, account);
 manager.persist(product);

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

谢谢你的回复,马雷克。就我而言,账户也是一个实体;如果我在createProduct()方法中创建帐户实例,是否会导致冲突?应该与Product(@Entity和others)的方法相同。EM非常聪明,可以处理这一点:)记住将这两个类都放在persistence.xmlCheers mate!这给了我一些关于发生了什么的解释:D