简体   繁体   中英

Database manipulation in Java EE

I know the usual way of connecting Java application to to the database using the following code:

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

How about in Java EE? Is there a new approach in database manipulation or should I use the same code above?

If you are using Java EE, you should use the Java Persistence API (JPA).
1. You should create a data source in your container.
2. Configure the persistence.xml in your project.
3. Inject the EntityManager (javax.persistence.EntityManager) object with the @PersistenceContext (javax.persistence.PersistenceContext) annotation.
4. And, use it. For example

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);
}

I hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM