我通常使用 持久性.xml 等属性来配置休眠。
<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" />
<!-- ... -->
然而,我需要在运行时改变一个属性(更具体地说,我需要调整以下属性的值 javax.persistence.query.timeout
在运行时)。) 因此,我试着在需要非默认属性的情况下手动配置会话,就像那样。
Configuration config = new Configuration();
config.addResource("persistence.xml");
config.setProperty("javax.persistence.query.timeout", "100000");
Session session = config.buildSessionFactory().getCurrentSession();
然而,这产生了以下异常
org.hibernate.boot.MappingNotFoundException: Mapping (RESOURCE) not found : persistence.xml : origin(persistence.xml)
这是有道理的,因为 持久性.xml 并不是一个普通的hibernate资源文件。那么,如何在配置的基础上,设置好 persistenc.xml 我不想把所有的属性配置两次)?或者更一般地说,我如何在运行时重新配置hibernate?
需要注意的是,这类似于,但不重复(因为它更具体)。此职位.
它可以在每个查询中被重写。
query.setHint("javax.persistence.query.timeout", 5000); // 5 seconds
如果你的查询对象是org.hibernate.Query类型,你可以这样做:
query.setTimeout(5);
https:/docs.jboss.orghibernateorm3.2apiorghibernateQuery.html#setTimeout(int)
在运行时改变EntityManagerFactory中的属性(影响所有的查询)将不会改变有效的配置.如果你想的话,你可以完全创建一个新的EntityManagerFactory,这里有描述。动态地改变持久单元 - JPA