【问题标题】:JPA controller & database. Web serviceJPA 控制器和数据库。网络服务
【发布时间】:2013-05-30 16:58:13
【问题描述】:

我在 netbeans 上创建了一个访问本地数据库的 RESTful Web 服务。 我查看了 netbeans 的示例项目,他们使用 JPA 控制器。 这个问题可能很基础,但我没有太多时间深入研究 JPA。

谁能解释为什么需要使用 JPA 控制器?

另外,我阅读了上一个问题,“通过 JPA 访问数据库表与 Web 应用程序中的 EJB”,它建议使用 EJB。

再次,可以解释一下吗?

公共类 CustomerJpaController 实现可序列化 {

public CustomerJpaController(UserTransaction utx, EntityManagerFactory emf) {
    this.utx = utx;
    this.emf = emf;
}
private UserTransaction utx = null;
private EntityManagerFactory emf = null;

public EntityManager getEntityManager() {
    return emf.createEntityManager();
}

public void create(Customer customer) throws PreexistingEntityException, RollbackFailureException, Exception {
    EntityManager em = null;
    try {
        utx.begin();
        em = getEntityManager();
        em.persist(customer);
        utx.commit();
    } catch (Exception ex) {
        try {
            utx.rollback();
        } catch (Exception re) {
            throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
        }
        if (findCustomer(customer.getCustomerId()) != null) {
            throw new PreexistingEntityException("Customer " + customer + " already exists.", ex);
        }
        throw ex;
    } finally {
        if (em != null) {
            em.close();
        }
    }
}

【问题讨论】:

    标签: web-services jpa


    【解决方案1】:

    我从未听说过“JPA 控制器”,但通常将 JPA 代码嵌入某种服务类中以处理事务。

    无状态 EJB bean 非常适合这种情况。如果没有它们,您将不得不手动启动、提交和回滚事务,这很乏味、冗长且容易出错。使用 EJB,这变得微不足道,因为它们透明地为您管理事务。

    【讨论】:

    • 这是来自上述课程的 sn-p。客户类是数据库实体。 @迈克
    • @user1960972 您展示的内容确实类似于服务。查看所有事务处理代码和 EM 的关闭。有了 EJB,这一切都消失了。你注入 EM,调用它的查询,就是这样。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-25
    • 2020-02-20
    • 2015-08-15
    相关资源
    最近更新 更多