Reputation: 103
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
Upvotes: 1
Views: 2048
Reputation: 2461
In JSF managed beans there are no implicit transactions. The only way to avoid managing the transactions manually would be to create an EJB in the application server, and have the JSF managed bean call it to persist data. You are using GlassFish, so using EJB would be possible... but it is definitely a new level of complexity. A great way to handle persistence transactions is to have a try-catch block template like this:
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();
}
It is not as clean looking as the super slick CDI and automatic transactions, but it will handle transactions properly, and ensure data integrity.
Upvotes: 1