I'm currently having problem with executing transaction inside stateless session.
On a service layer i have defined transaction using #Transactional annotation (which is required because the methods needs to be in one transaction).
Inside the method I create new entity Car.
However I also have to create in underlaying methods custom transtaction inside stateless session (its done for performance) like this
StatelessSession session = getSessionFactory().openStatelessSession();
Transaction transaction = session.beginTransaction()
// create and setup CarRequirements entity
transaction.commit;
Problem is that the entity CarRequirements has foreign key to entity Car. Therefore when i try to commit the underlaying transaction an exception occurs because obviously the Car entity is not yet commited to database.
Is there a way to postpone the commit of underlaying transaction or force commit of the Car entity?
either you define a relationship between CarRequirements and Car (cascade)
or you have to save a Car firstly then save CareRequirements
Related
I'm currently implementing my first spring boot application after years of JEE.
I am wondering about JPA / Hibernate behaviour. In JEE, once persisted or "find" an #Entity, all changes to this Entity are populated automatically by the JPA implementation to the database without any need to call persist(), flush() etc.
Now with a CrudRepository changes are only stored to the database if I explicitely call save().
My CrudRepository:
public interface UserAccountRepository extends CrudRepository<UserAccount, Long> {
public Optional<UserAccount> findByEmail(String email);
public Optional<UserAccount> findByVerificationCode(String verificationCode);
}
Example code:
public void updateUser(Long userId, String newName) {
UserAccount userAccount = userAccountRepository.findById(userId)
.orElseThrow(() -> new NotFoundException("Userid not found"));
userAccount.setLastName(newName);
//Stop here in JEE
userAccountRepository.save(userAccount);
}
In a JEE implementation right after .setLastName the change would be persisted to the database by Hibernate. In my spring-boot service it istn't. It's usually explicitely necessary to issue .save() any idea why and how I could gain the same behaviour like in JEE?
Actually Spring boot Repository uses JPA behind the scene to persist entity to the database. but I want to explain what happen behind the scene. You know there is an EntityManager which has a Persistence Context. When EntityManager created, it will attach itself to the current TransactionManager so that when that transaction committed all data within that Persistence Context will be committed to the database or on the other hand when transaction RollBack all data within that Persistence Context will be roll backed. Here in Spring Repository you can see that there is no Persistence Context explicitly. This Persistence Context exist but works behind the scene and when findById method return and deliver you the entity, that entity is not attached to persistence Context actually this context is closed when findById return.
But Spring Repository make all this proccess transparent to the user since it uses EntityManager and Transaction Manager behind the scene. actually it is the magic wand of Spring that let you omit all these boilerplate code. But this magic didn't come without any drawback, in your updateUser method you don't open and you don't commit any transaction but they acctually opened and committed two times behind the scene, once when you call findById method, it open transaction, fetch data and commit it. And again when you save data here again transaction open, and Persistence Context content save to database when transaction committed. imagine you have some transactional process in your special method in that case you should think about that specially.
I have the code from below and wondering how does JPA know to persist this update. I expected an em.merge() to be needed in order to perform the update. Is this actually safe ?
#Stateless
class User {
...
public void generateRandomNicknames() {
List<UserEntity> users = em.createNamedQuery("UserEntity.getAllUsers", UserEntity.class)
.getResultList();
for (UserEntity user : users) {
user.setNickname(generateRandomNickname());
}
// em.merge(user) or em.persist(user) not needed ?
}
}
In short: Managed entities are generally synchronized with the database on transaction commit. The JPA implementation is responsible for tracking changed managed entities and update the database. In your case, calling user.setNickname(...) will notify JPA that this specific user object is dirty. And a transaction is by default active on calling business methods of a Session EJB.
Note that the above is the default behavior that can be altered by configuration!
Longer story, with references from the JEE 8 sub-specs (the question is about JEE 6, these still apply, although in different section numbers):
(JPA 2.1) Section 3.2.4: Synchronization to the Database
The state of persistent entities is synchronized to the database at transaction commit. This synchronization
involves writing to the database any updates to persistent entities and their relationships as specified
above.
[...]The persistence provider runtime is permitted to perform synchronization to the database at other times
as well when a transaction is active and the persistence context is joined to the transaction. The flush
method can be used by the application to force synchronization.
There are other interesting details in this chapter, but note that merge() does NOT have to be called, for a managed entity to be saved at the end of the transaction.
Which brings us to the next detail, the transaction. Since this is a method of a Session EJB, it is by default run in the context of a transaction:
(EJB core 3.2) Section 8.3.6: Specification of a Bean’s Transaction Management Type
By default, a session bean or message-driven bean has container managed transaction demarcation if the transaction management type is not specified. [...]
(EJB core 3.2) Section 8.3.7: Specification of the Transaction Attributes for a Bean’s Methods
The Bean Provider of an enterprise bean with container-managed transaction demarcation may specify the transaction attributes for the enterprise bean’s methods. By default, the value of the transaction attribute for a method of a bean with container-managed transaction demarcation is the REQUIRED transaction attribute, and the transaction attribute does not need to be explicitly specified in this case.
An important detail is that the entities are actually managed. This is, in this case, because they are returned from JPA itself and because of how the JPQL query "UserEntity.getAllUsers" is structured. In general entities could be unmanaged or detached, in which case calling merge() or persist() would have been necessary.
I need to create a simple JEE application which could have two modes. First, it automatically stores each modification to the database, and second, all the changes are stored on demand. Is it possible to start one JPA transaction and span it over many postbacks on a given stateful bean and commit changes (or rollback) when a user clicks some button?
I tried to set the following parameters on my bean:
#Stateful
#TransactionManagement(TransactionManagementType.BEAN)
and also for EntityManager:
#PersistenceContext(type = PersistenceContextType.EXTENDED)
but I get the following exception when I try to commit:
java.lang.IllegalStateException: Transaction is not active in the current thread.
If it is not possible like that, what is the easiest way to create the above functionality?
It is because you forgot to open a transaction. You made everything correct, but additional you have to inject in your #Stateful bean a UserTransaction (given your PersistenceContext is JTA and not RESOURCE_LOCAL) and then to start a transaction before comitting the changes.
As we all know that in Hibernate if no transaction commit, the changes won't affect in database. But I found something weird. And the code as follows:
ApplicationContext ctx = new ClassPathXmlApplicationContext("Spring.xml");
SessionFactory sessionFactory = (SessionFactory) ctx.getBean("sessionFactory");
Session session = sessionFactory.openSession();
Model model = new Model();
...
session.save(model);
session.flush();
session.close();
And the model was saved to database even there's no transaction, anyone can explain this?
Any comments would be appreciated! Thanks!
PS: I am using mysql.
The session.flush command saved the transaction. If it's wrong, you should use transaction.
usually hibernate needs the line session.beginTransaction(); to work. You didn't write that and your application worked, I guess your application runs in an Application server, which provides transaction management. e.g. jboss, weblogic...
However it doesn't mean that there is no transaction. Did you set auto-commit true?
btw, session.flush() and txn.commit() are different.
Flushing is the process of synchronizing the underlying persistent store with persistable state held in memory.
After session.flush(), you still can call txn.rollback() to rollback all changes.
edit
oh I saw you used spring. did you configured txnmanager in spring?
Hibernate doesn't need transactions, the most common problems in database-based applications are just easier to solve with transactions which is why usually everyone uses transactions with Hibernate. But that's mere coincidence/convention/laziness.
All Hibernate needs is a java.sql.Connection and if your container provides one even though there is no current transaction manager configured, Hibernate is fine with that.
In fact, Hibernate has no idea that there might be a transaction manager. So session.flush() will use the ApplicationContext to get a connection, generate the SQL and use JDBC to send the generated SQL code to the database.
From Hibernate's point of view, that's all that happens.
There can be several reasons why the data is committed to the database:
You forgot to turn of auto commit on the connection.
Your web container / spring config automatically wires a transaction manager that synchronizes with HTTP requests.
Your code is called form another method which is annotated with #Transactional; in this case, you inherit the existing transaction.
Can #PersistenceUnit be used with JTA in JPA? If so, how is it possible?
Per http://tomee.apache.org/jpa-concepts.html:
With <persistence-unit transaction-type="RESOURCE_LOCAL"> [...]
You must use the EntityManagerFactory to get an EntityManager
[...]
An EntityManagerFactory can be injected via the #PersistenceUnit annotation only (not #PersistenceContext)
With <persistence-unit transaction-type="JTA"> [...]
An EntityManager can be injected via the #PersistenceContext annotation only (not #PersistenceUnit)
I have a similar code which uses JTA and #PersistenceUnit at the same time. But sometimes I am having NullPointerException when accesing transaction (defined as #Resource).
Using JTA means that you delegate the work to the container. You can override it by using a UserTransaction. Your quotation contains all the answers you want to know. Using PersistenceUnit to get an EntityManager won't work.
If you are using RESOURCE_LOCAL you are responsible for the transaction itself, by using EntityManager.getTransaction(). An entity manager is created by an EntityManagerFactory. To obtain that factory, you can use PersistenceUnit.
So the simple answer is no, if you rely on container managed entity managers.
As example see http://docs.oracle.com/javaee/6/tutorial/doc/bnbqw.html
Application Managed Entity Managers = RESOURCE_LOCAL can use UserTransaction (which are part of JTA).
What does entity manager means???
If i am a naive programmer i could simply interpret something which manages entity & Indeed it means the same.
An Entity Manager is been instantiated with the help of an Entity Manager Factory. A connection to a database is managed by the entity manager i.e. it provides functionality for performing operations on a database. Therefore we could say if an application needs multiple database connections, an EntityManagerFactory will be constructed for a specific database which provides an efficient way to construct multiple EntityManager instances(if required, even single instance of entity manager can the job depending upon the requirement you may opt for multiple instances) for that database required for every HTTP request. We shall understand this with the help of an example. Suppose we have a
Database : A , having a relational tables B and C.
So for A, an instance of entity manager factory will be instantiated. Now we if ever want to perform any update to table B & lets say delete operation for table C, either two different entity manager could be instantiated or same the entity manager instance can be utilized for both.
The instantiation of Entity Manager Factory itself is considered to be less efficient but since it's a one time activity therefore it's manageable task because Entity Manager Factory once instantiated, it will serve the entire application
The entity manager instantiated is associated with a persistence context.
#PersistenceUnit(unitName = "MyDatabase")
EntityManagerFactory emf;
EntityManager entityManager = emf.createEntityManager();
or
#PersistenceContext(unitName = "MyDatabase")
private EntityManager entityManager;
PersistenceUnit injects an EntityManagerFactory, and PersistenceContext injects an EntityManager. It's generally better to use PersistenceContext unless you really need to manage the EntityManager lifecycle manually.
EntityManagerFactory defines another method for instantiation of EntityManager that, like the factory, takes a map of properties as an argument. This form is useful when a user name and a password other than the EntityManagerFactory's default user name and password have to specified:
Map properties = new HashMap();
properties.put("javax.persistence.jdbc.user", "kashyap");
properties.put("javax.persistence.jdbc.password","kashyap");
EntityManager em = emf.createEntityManager(properties);
Within the persistence context, the entity instances and their lifecycle are managed. By Entity instance, we mean instance of an entity & each entity designates relational table in the database. Entity Manager is actually an interface which provides methods to create and remove persistent entity instances, to find entities by their primary key, and to query over entities so together these functionalities are grouped under operations we perform. Operations that modify the content of a database require active transactions. Transactions are managed by an Entity Transaction instance obtained from the EntityManager.
Precise Definition :-
An Entity Manager is defined by a persistence unit. A persistence unit defines the set of all classes that are related or grouped by the application, and which must be colocated in their mapping to a single database.
Below i'm writing a code snippet for better understanding :-
try {
em.getTransaction().begin();
// Operations that modify the database should come here.
em.getTransaction
/**
*getTransaction() EntityManager's method Return the resource-level EntityTransaction object. See JavaDoc Reference Page
*/
em.getTransaction().commit();
}
finally {
if (em.getTransaction().isActive())
em.getTransaction().rollback();
}
Lets proceed as per JPA Specification :-
1) Extended vs Transactional - Scoped :
By Default the Transactional Persistence Context is in used which means all changes are flushed and all managed entities become detahced when the current transaction commits.
The Extended scope is available only for Stateful EJBs & it even makes a perfect sense since stateful beans can save the state therefore one can say end of
one business method doesn't necessary means the end of the transaction.
With the Stateless beans, it has a different aspect - We have business method that must end when the business method finishes.
===> One Method = One Transaction;
Only Transactional-Scoped Entity Manager is allowed for Stateless Beans
You can control if the EntityManager is extended or transactional during the EntityManager Injection :-
#PersistenceContext (type = javax.persistence.PersistenceContextType.EXTENDED)
EntityManager emng;
By Default it's javax.persistence.PersistenceContextType.TRANSACTION
Extended and Transaction Scoped PersistenceContext are allowed only in case of container-managed EntityManagers.
Time to step up a bit with: Container-managed vs Application-managed
2) Container-managed vs Application-managed :
#PersistenceContext
EntityManager emng;
Above statement authorises Container to inject the entity manager for you, hence Container-Managed.
Alternatively, you can create an EntityManager by yourself using EntityManagerFactory But this time the injection will be bit different -
#PersistenceUnit
EntityManagerFactory emf;
Now to get the EntityManager you need to invoke
emf.createEntityManager();
And here it is - you're using the application managed Persistence Context. Now you're responsible for creation and removal of EntityManagers.
Focus before you read the next para because that's what the tangled context , i'm trying to resolve-
You might use createEntityManager if you want to have control over created EM - e.g. if you need to move the created EntityManager across multiple beans involved in the trasaction - the container won't do it for you and every time you invoke createEntityManager(), you're creating an EntityManager that is connected to the new PersistenceContext. You might use the CDI for EntityManager's sharing.
Stay tuned for Entity Transaction - JPA and Resource-local, will be posting a detailed discussion on it.
Hope it gives a brief idea about the context. & Feel free to post queries.
Read the second part from here