2015-04-27 32 views
0

我知道用下面的代碼連接Java應用程序到數據庫的常用方法:在Java EE的數據庫操作

Class.forName("com.mysql.jdbc.Driver"); 
DriverManager .getConnection("jdbc:mysql://localhost/......."); 

如何在Java EE的?數據庫操作中有新的方法,還是應該使用上面的相同代碼?

+4

您可能想在容器中設置數據源,然後在需要時將其注入。或者注入一個PersistenceContext並使用JPA。 – Bill

回答

1

如果您使用的是Java EE,則應使用Java Persistence API(JPA)。
1.您應該在容器中創建一個數據源。
2.在項目中配置persistence.xml。
3.使用@PersistenceContext(javax.persistence.PersistenceContext)批註注入EntityManager(javax.persistence.EntityManager)對象。
4.然後使用它。例如

public YourObject findById(Integer id) { 
    return em.find(YourObject.class, id); 
} 
public void persist(YourObject entity) { 
    em.persist(entity); 
} 
public void update(YourObject entity) { 
    em.merge(entity); 
} 
public void delete(YourObject entity) { 
    em.remove(entity); 
} 

我希望它有幫助。