简体   繁体   English

Java EE中的数据库操作

[英]Database manipulation in Java EE

I know the usual way of connecting Java application to to the database using the following code: 我知道使用以下代码将Java应用程序连接到数据库的通常方法:

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

How about in Java EE? 在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). 如果您使用的是Java EE,则应使用Java Persistence API (JPA)。
1. You should create a data source in your container. 1.您应该在容器中创建一个数据源。
2. Configure the persistence.xml in your project. 2.在您的项目中配置persistence.xml。
3. Inject the EntityManager (javax.persistence.EntityManager) object with the @PersistenceContext (javax.persistence.PersistenceContext) annotation. 3.使用@PersistenceContext(javax.persistence.PersistenceContext)注释注入EntityManager(javax.persistence.EntityManager)对象。
4. And, use it. 4.然后使用它。 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. 希望对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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