javahibernatejpapersistence.xml

Change hibernate JPA properties at runtime


I usually use a persistence.xml to configure hibernate, via properties like

<properties>        
    <property name="javax.persistence.lock.timeout" value="90000"/>
    <property name="javax.persistence.query.timeout" value="90000" />
    <property name="hibernate.dialect" value="org.hibernate.dialect.SQLServer2012Dialect" />
<!-- ... -->

However, I need to change one property at runtime (more specifically I need to adjust the value of javax.persistence.query.timeout at runtime). Therefore I tried configuring the session manually in situations where I need non-default properties, like that:

Configuration config = new Configuration();
config.addResource("persistence.xml");
config.setProperty("javax.persistence.query.timeout", "100000");
Session session = config.buildSessionFactory().getCurrentSession();

However, this yields the following exception:

org.hibernate.boot.MappingNotFoundException: Mapping (RESOURCE) not found : persistence.xml : origin(persistence.xml)

Which makes sense, as the persistence.xml isn't a normal hibernate resource file. So how do I set the configuration on the basis of the persistenc.xml (I don't want to configure all the properties twice)? Or more generally, how do I reconfigure hibernate at runtime?

Note that this is similar to, but not duplicating (as it's more specific), this post.


Solution

  • It can be overridden/set per query:

    query.setHint("javax.persistence.query.timeout", 5000); // 5 seconds
    

    If your query object is of type org.hibernate.Query you can do:

    query.setTimeout(5);
    

    https://docs.jboss.org/hibernate/orm/3.2/api/org/hibernate/Query.html#setTimeout(int)

    Changing the properties in the EntityManagerFactory at runtime (To affect all queries) will not change the configuration in effect. You can create a new EntityManagerFactory altogether if you want to, described here: Changing Persistence Unit dynamically - JPA