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.