2014-04-15 34 views
0

美好的一天,如何正確使用entitymanager創建實體對象?

我目前在我的第一個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(); 

} 
} 

能否請您給我的代碼的例子,我要開始之間寫下()和commit()行在我的createProduct方法中;另外,如果你能解釋entitymanager是如何工作的,我將不勝感激。我已閱讀了幾篇關於這方面的文檔,但仍需要澄清。

在此先感謝

回答

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

當你把你的註釋像@Column @OneToOne等人對字段或干將的EntityManager會用這種方式來從類獲取一個字段的值根據。它使用反射來讀取註釋,並通過使用它來知道表應該是什麼樣子。通過了解表結構,它只是在後臺將查詢發送到數據庫。當你創建一個實體管理器工廠時,基本上對這些類進行分析,這個操作通常非常耗時(取決於db結構)。爲了低調地工作,閱讀更多關於反思的內容。如果你得到反思,你會得到多麼簡單。

+0

謝謝你的回覆馬雷克。就我而言,賬戶也是一個實體;如果我將在createProduct()方法中創建一個帳戶實例,它會導致任何衝突嗎? – Bravo

+0

應該和產品(@Entity和其他)一樣。 EM是如此聰明,可以處理這個:)記得把這兩個類放在persistence.xml –

+0

乾杯隊友!這給了我一些解釋:D – Bravo