1

I m trying to integrate Spring and JSF i stuck on persisting object. I dont want to handle transaction (begin - commit etc)

After some googling i could find an answer give what i need in this link

I'm using eclipselink as ORM and Oracle 11g database and Glassfish server 3.1 with maven. I prefered annotation for Spring configuration. I use

@Transactional
@Service

annotations in related class. My persistence.xml name is E_DefterManagementPU and my transaction-type is JTA. Here is my code to persist efaFunctions

public EntityManager entityManager;

@Inject
public void setEntityManager() {
    EntityManagerFactory emf = Persistence.
            createEntityManagerFactory("E_DefterManagementPU");
    this.entityManager = emf.createEntityManager();
}    

public void create(EfaFunctions efaFunctions) {              
    entityManager.persist(efaFunctions);  
}

Entity manager is not null and i can see **assign sequence to the object ** log on glassfish but he other logs are not generated but if i write the code below whic invisible parts are same with aboe code block ;

public void create(EfaFunctions efaFunctions) {       
    entityManager.getTransaction().begin();
    entityManager.persist(efaFunctions);  
    entityManager.getTransaction().commit();
}

it persists the object. This works but i dont want to handle begin() commit() parts and according resources with JTA Container Managed Persistence should do this instead of me. Can any body tell me where i m wrong Thanks in advance

4

1 回答 1

1

在 JSF 托管 bean 中没有隐式事务。避免手动管理事务的唯一方法是在应用程序服务器中创建一个 EJB,并让 JSF 托管 bean 调用它来持久化数据。您正在使用 GlassFish,因此可以使用 EJB……但这绝对是一个新的复杂程度。处理持久性事务的一个好方法是有一个这样的 try-catch 块模板:

    EntityManager em = ... //However you get an em.
    try {
        em.getTransaction().begin();

        // ...  Put your persistence code here.

        em.getTransaction().commit();
    } catch (Exception ex) {
        em.getTransaction().rollback();
        throw ex;
    }finally {
        em.close();
    }

它不像超级光滑的 CDI 和自动事务那样干净,但它会正确处理事务,并确保数据完整性。

于 2013-05-13T21:48:36.923 回答