用 Hibernet Tool 自動產生的 Domain Code,對於 FOREIGN KEY 會以 annotation: @ManyToMany(fetch = FetchType.LAZY) 來作註,但執行時會發生下列的錯誤
Struts Problem Report
Struts has detected an unhandled exception:
Messages: |
- failed to lazily initialize a collection of role: com.mis.model.Admin.roles, could not initialize proxy - no Session
|
File: |
org/hibernate/collection/internal/AbstractPersistentCollection.java |
|
Stacktraces
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.mis.model.Admin.roles, could not initialize proxy - no Session
|
解決方法: 由 FetchType.LAZY 改成 FetchType.EAGER
//@ManyToMany(fetch = FetchType.LAZY)
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "admin_roles", catalog = "weixin", joinColumns = {
@JoinColumn(name = "aid", nullable = false, updatable = false) }, inverseJoinColumns = {
@JoinColumn(name = "rid", nullable = false, updatable = false) })
public Set<Role> getRoles() {
return this.roles;
} |
或者是在 applicationContext.xml 加入 <prop key="hibernate.enable_lazy_load_no_trans">true</prop> 如下
<!-- Configure the entity manager factory bean : Step02-Start-->
<bean id="emfLocalDS" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="LocalDS"></property>
<property name="persistenceUnitName" value="emfLocalPU"/>
<!-- Set base package of your entities -->
<property name="packagesToScan" value="com.mis.model"/>
<!-- Set share cache mode -->
<property name="sharedCacheMode" value="ENABLE_SELECTIVE"/>
<!-- Set validation mode -->
<property name="validationMode" value="NONE"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="MYSQL" />
<property name="showSql" value="true" />
</bean>
</property>
<!-- Set JPA properties -->
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key="hibernate.enable_lazy_load_no_trans">true</prop>
</props>
</property>
</bean>
<!-- Configure the entity manager factory bean : Step02-End-->
|
參考:
http://stackoverflow.com/questions/11746499/solve-failed-to-lazily-initialize-a-collection-of-role-exception
http://www.lostinsoftware.com/2015/08/reverse-engineering-and-code-generation/
留言列表