好吧,我放弃了接受答案。我仔细检查了Hibernate源代码,并得出结论:Hibernate本身不具备实现我所希望的属性。但是我想出了一个肮脏的技巧,这正是我想要的。因此,这里是:
public class DirtyHackedHibernatePersistence extends HibernatePersistence { @Override @SuppressWarnings({ "rawtypes", "unchecked" }) public EntityManagerFactory createEntityManagerFactory(String persistenceUnitName, Map properties) { properties.put(AvailableSettings.PROVIDER, HibernatePersistence.class.getName()); Ejb3Configuration cfg = new Ejb3Configuration().configure(persistenceUnitName, properties); if (cfg == null) { return null; } cfg.buildMappings(); hackConfiguration(cfg); return cfg.buildEntityManagerFactory(); } @Override @SuppressWarnings({ "rawtypes", "unchecked" }) public EntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo info, Map properties) { properties.put(AvailableSettings.PROVIDER, HibernatePersistence.class.getName()); Ejb3Configuration cfg = new Ejb3Configuration().configure(info, properties); if (cfg == null) { return null; } cfg.buildMappings(); hackConfiguration(cfg); return cfg.buildEntityManagerFactory(); } private void hackConfiguration(Ejb3Configuration cfg) { System.out.println("Hacking configuration"); String noProxyByDefault = cfg.getProperties().getProperty("hibernate.hack.no-proxy-by-default", "false"); if (Boolean.parseBoolean(noProxyByDefault)) { Iterator<?> iter = cfg.getClassMappings(); while (iter.hasNext()) { hackClass((PersistentClass)iter.next()); } } } private void hackClass(PersistentClass classMapping) { Iterator<?> iter = classMapping.getPropertyIterator(); while (iter.hasNext()) { Property property = (Property)iter.next(); if (property.getValue() instanceof ToOne) { ToOne toOne = (ToOne)property.getValue(); if (toOne.isLazy()) { toOne.setUnwrapProxy(true); } } } }}
还必须有一个名为资源的资源,
meta-INF/services/javax.persistence.spi.PersistenceProvider其中包含带有类名称的一行。
要使用此技巧,您应在中指定以下内容
persistence.xml:
<provider>packagename.DirtyHackedHibernatePersistence</provider><properties> <property name="hibernate.hack.no-proxy-by-default" value="true"/></properties>
完整的示例可在此处获得。
请注意,如果删除该
hibernate.hack.no-proxy-by-default属性并重建项目,则两个断言都会被破坏。
我还将向Hibernate团队发布功能请求。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)