How can I force Hibernate to update an entity instance even if the entity is not dirty? I'm using Hibernate 3.3.2 GA, Hibernate Annotations and Hibernate EntityManager btw. I really want Hibernate to execute the generic UPDATE statement even if no property on the entity has changed.
I need this because some event listeners need to get invoked to do some additional work when the application runs for the first time.
Thanks!
ok - found it myself. This does the trick:
Session session = (Session)entityManager.getDelegate();
session.evict(entity);
session.update(entity);
For transients, you can check
if(session.contains(entity)) {
session.evict(entity);
}
session.update(entity);
session.evict(entity);
session.update(entity);
Good trick, but watch out for transient objects before putting this into some automation code. For transients I have then StaleStateObjectException
Try em.flush() which is used for EJB 3.0 entities, which also uses JPA similar to Hibernate 3.2.2 GA. If it doesn't work normally, use flush in transactions.
Related
I'm trying to get performance data from Hibernate OGM. It doesn't seem to have the Hibernate statistics classes like Hibernate ORM. Is there something equivalent?
The reason there are not specific classes is that you should be able to use the existing one in ORM.
For example:
org.hibernate.stat.Statistics statistics = getSessionFactory().getStatistics();
statistics.setStatisticsEnabled( true );
final Session session = openSession();
...
statistics.logSummary();
session.close();
If you think that something is missing or not working, you can signal it on the Hibernate OGM Jira or forum.
Davide
I got to know about possibility of Dynamic entity creation in eclipselink from here. And I'm trying to create Dynamic entities and map them to static entities which are already present in the same persistence unit as described in the examples given here.
I'm using refreshMetadata(with empty map of properties) of EntityManagerFactoryImpl to refresh metadata.
But the the dynamic entities are not getting listed in the metamodel of entitymanager factory.
Can somebody let me know where am I going wrong?
I expect they won't, as the Dynamic entity api adds mappings to the native EclipseLink session, while the JPA metamodel is build from JPA mappings. refreshMetadata is used to rebuild the native EclipseLink session using any new JPA metadata (orm.xml etc), but does not go the other way.
I was able to refresh the metamodel by adding a new metamodel with the current session by the following code snippet:
Metamodel metamodel = new MetamodelImpl((AbstractSession) dynamicHelper.getSession());
((EntityManagerFactoryImpl) emf).setMetamodel(metamodel);
Though this didn't solved my main problem, it solved the problem I've asked here.
I started working on a new project using Playframework and thought to try using it with Ebean ORM. What i am wondering now is if Play with the Ebean implementation supports managed entities and if so ..how? Take this example method from the controller:
#Transactional
public Result changePassword() {
Long userId = Long.valueOf(session("id"));
User user = User.find.byId(userId);
user.setName("John Doe");
}
Is there any way to persist the changes to the database when the transaction ends? Currently what i am doing is calling user.save(). This is not much but working with JEE/JPA (and recently Dropwizard) i got used to have my entities changes persisted when the transaction ends.
No, I don't think Play natively supports something like auto save transaction as you want. Explicit save method is the only option.
Ebean.save(xyz);
General suggestion on your code, From Play 2.3.x, In your case, No need to annotate or explicitly mention the transaction, if Save is the only action on User EBean. By default each action on EBeans will be executed in separate transactions. Can specify the transaction explicitly if multiple actions need to be executed in single transaction.
Is it possible to stop hibernate from auto updating a persistent object?
#Transactional
public ResultTO updateRecord(RequestTO requestTO) {
Entity entity = dao.getEntityById(requestTO.getId());
// now update the entity based on the data in the requestTO
ValidationResult validationResult = runValidation(entity);
if(validationResult.hasErrors()) {
// return ResultTO with validation errors
} else {
dao.persist(entity);
}
}
Here is what happens in the code, I retrieve the entity which would be considered by hibernate to be in persistent state, then I update some of the fields in the entity, then pass the entity to validation. if validation fails, then don't udpate, if validation succeeds then persist the entity.
Here is the main issue with this flow: because I updated the entity for it to be used in the validation, it does not matter whether I call persist() method (on the DAO) or not, the record will always be updated because hibernate detects that the entity has been changed and flags it for update.
Keep im mind I can change the way i do validation and work around the issue, so I'm not interested in workarounds. I'm interested in knowing how i would be able to disable the hibernate feature where it automatically updates persistent objects.
Please keep in mind I'm using hibernates' implementation of JPA. so Hibernate specific answers dealing with hibernate specific API will not work for me.
I tried to look for hibernate configuration and see if I can set any configuration to stop this behavior but no luck.
Thanks
--EDIT ---
I couldn't find a solution to this, so I opted to rolling back the transaction without throwing any RuntimeException even though I'm in a declarative transaction using:
TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
which works like a charm.
Configure FlushMode for your session.
http://docs.jboss.org/hibernate/orm/3.5/api/org/hibernate/FlushMode.html
You can use EntityManager.clear() method after getting object from database.
http://docs.oracle.com/javaee/6/api/javax/persistence/EntityManager.html#clear()
You can call the following code:
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
Throw an exception if validation fails and have the caller handle that.
I have no DAO service layer in a spring MVC project. IN my controller, I wish to create a criteria query. For this I need a session object to call the "createCriteria(myClass.class)".
How do I get the session object ?
I saw some people were using the HibernateUtil class like "HibernateUtil.currentSession()". I tried this but the import cannot be resolved. I posted some of the relvant code to address another issue here Hibernate criteria queries - Query Conditions
Can someone please offer some form of guidance in this regard, Thanks.
HibernateUtil is a class you are supposed to create according to your own needs. Here's the corresponding docs section.
I would take a look at the dispatcher-servlet.xml. Sessions (Hibernate), tx managers are set up in the context for later access. old 2.5 example .. http://static.springsource.org/spring/docs/2.5.x/reference/orm.html
HibernateUtil is a class from the Hibernate tutorial. It's not for real use. Don't use it for anything but the tutorial. If you're already using Spring, it has excellent Hibernate integration. Just do it the right way from the start.
Ok, the problem was solved by using the entity manager exposed in the parent entity class. I have a class called person and in there is placed a transient method as follows
#Transient
public static Collection<?> searchResults(JsonJqgridSearchModel jsonJqgridSearchModel){
HibernateEntityManager hem = Person.entityManager().unwrap(HibernateEntityManager.class);
Session session = hem.getSession();
Criteria criteria = session.createCriteria(Person.class);
Iterator<JqgridSearchCriteria> iterator = jsonJqgridSearchModel.rules.iterator();
while(iterator.hasNext()){
criteria.add(iterator.next().getRestriction());
}
return criteria.list();
}
The main thing is how the HibernateEntityManager and the Session was obtained. Hope this helps someone out there.