lundi 2 mars 2015

Why Lazy Initialization Exception in Hibernate polymorphic Assosiation after making it FetchType.Eagar?

Getting Lazy Initialization Exception even after making FetchType.Eagar


I am trying something like this from spring service class



List<DeviceTree> deviceTree = deviceTreeRepository.findByCustomerId( customerId );

DeviceTree tree = deviceTree.get(0);
Node node = tree.getNode();
if(node instanceof Device){
System.out.println("Device");
Device dev= (Device)node;
System.out.println(dev.getIddevice());
System.out.println(dev.getIp());
}


But getting exception



org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:165)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:286)
at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:185)
at com.vuelogix.collygo.data.entities.Device_$$_jvst69a_3d.getIddevice(Device_$$_jvst69a_3d.java)
at com.vuelogix.collygo.data.services.impl.DeviceTreeService.findAll(DeviceTreeService.java:52)
at com.vuelogix.collygo.core.startup.LoadPdtSplitter.getSplit(LoadPdtSplitter.java:34)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.apache.camel.component.bean.MethodInfo.invoke(MethodInfo.java:407)
at org.apache.camel.component.bean.MethodInfo$1.doProceed(MethodInfo.java:278)
at org.apache.camel.component.bean.MethodInfo$1.proceed(MethodInfo.java:251)
at org.apache.camel.component.bean.BeanProcessor.process(BeanProcessor.java:166)
at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:105)
at org.apache.camel.component.bean.BeanProcessor.process(BeanProcessor.java:67)
at org.apache.camel.language.bean.BeanExpression$InvokeProcessor.process(BeanExpression.java:189)
at org.apache.camel.language.bean.BeanExpression.evaluate(BeanExpression.java:123)
at org.apache.camel.language.bean.BeanExpression.evaluate(BeanExpression.java:132)
at org.apache.camel.processor.Splitter.createProcessorExchangePairs(Splitter.java:103)
at org.apache.camel.processor.MulticastProcessor.process(MulticastProcessor.java:208)
at org.apache.camel.processor.Splitter.process(Splitter.java:98)
at org.apache.camel.management.InstrumentationProcessor.process(InstrumentationProcessor.java:72)
at org.apache.camel.processor.RedeliveryErrorHandler.process(RedeliveryErrorHandler.java:398)
at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:191)
at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:191)
at org.apache.camel.component.timer.TimerConsumer.sendTimerExchange(TimerConsumer.java:139)
at org.apache.camel.component.timer.TimerConsumer$1.run(TimerConsumer.java:64)
at java.util.TimerThread.mainLoop(Timer.java:555)
at java.util.TimerThread.run(Timer.java:505)


Here is my DeviceTree Entity. I have node_id which can either be a device or a logical group. I was trying to implement Hibernate Polymorphic Assosiation .



@Entity
@Table(name = "device_tree")
@NamedQuery(name = "DeviceTree.findAll", query = "SELECT d FROM DeviceTree d")
public class DeviceTree implements Serializable {
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "iddevice_tree")
private int iddeviceTree;

@Column(name = "customer_id")
private int customerId;

@Column(name = "is_disabled")
private boolean isDisabled;

private int lft;

@Column(name = "node_id")
private int nodeId;

@Any( fetch=FetchType.EAGER,metaColumn = @Column(name = "node_type_id"))
@AnyMetaDef(idType = "integer", metaType = "integer", metaValues = {
@MetaValue(targetEntity = Device.class, value = "1"),
@MetaValue(targetEntity = LogicalGroup.class, value = "2") })
@JoinColumn(name = "node_id" , insertable=false ,updatable=false)
private Node node;

@Column(name = "node_name")
private String nodeName;

@Column(name = "parent_id")
private Integer parentId;

private int rgt;

// uni-directional many-to-one association to Location
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "location_id")
@Fetch(FetchMode.JOIN)
private Location location;

// uni-directional many-to-one association to NodeType
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "node_type_id")
@Fetch(FetchMode.JOIN)
private NodeType nodeType;

// uni-directional many-to-one association to StatusDetail
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "status_details_id")
@Fetch(FetchMode.JOIN)
private StatusDetail statusDetail;

public DeviceTree() {
}

public int getCustomerId() {
return customerId;
}

public int getIddeviceTree() {
return iddeviceTree;
}

public int getLft() {
return lft;
}

public Location getLocation() {
return location;
}

public int getNodeId() {
return nodeId;
}

public String getNodeName() {
return nodeName;
}

public NodeType getNodeType() {
return nodeType;
}

public int getRgt() {
return rgt;
}

public StatusDetail getStatusDetail() {
return statusDetail;
}

public boolean isDisabled() {
return isDisabled;
}

public void setCustomerId(int customerId) {
this.customerId = customerId;
}

public void setDisabled(boolean isDisabled) {
this.isDisabled = isDisabled;
}

public void setIddeviceTree(int iddeviceTree) {
this.iddeviceTree = iddeviceTree;
}

public void setLft(int lft) {
this.lft = lft;
}

public void setLocation(Location location) {
this.location = location;
}

public void setNodeId(int nodeId) {
this.nodeId = nodeId;
}

public void setNodeName(String nodeName) {
this.nodeName = nodeName;
}

public void setNodeType(NodeType nodeType) {
this.nodeType = nodeType;
}

public void setRgt(int rgt) {
this.rgt = rgt;
}

public void setStatusDetail(StatusDetail statusDetail) {
this.statusDetail = statusDetail;
}

public Integer getParentId() {
return parentId;
}

public void setParentId(Integer parentId) {
this.parentId = parentId;
}

public Node getNode() {
return node;
}

public void setNode(Node node) {
this.node = node;
}


}


This is my Device class



@Entity
@Table(name = "device")
@Cacheable
@Cache( usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE )
@NamedQuery( name = "Device.findAll", query = "SELECT d FROM Device d" )
public class Device implements Serializable ,Node{
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue( strategy = GenerationType.IDENTITY )
private int iddevice;

@Temporal( TemporalType.TIMESTAMP )
@Column( name = "connection_status_update_time" )
private Date connectionStatusUpdateTime;

@Temporal( TemporalType.TIMESTAMP )
@Column( name = "creation_time" )
private Date creationTime;

@Column( name = "customer_id" )
private int customerId;

@Column( name = "description" )
private String description;

@Column( name = "ip" )
private String ip;

@Column( name = "location" )
private String location;

@Column( name = "name" )
private String name;

@Column( name = "port" )
private int port;

@Column( name = "serial_key" )
private String serialKey;

@Temporal( TemporalType.TIMESTAMP )
@Column( name = "system_status_update_time" )
private Date systemStatusUpdateTime;

@Column( name = "user_id" )
private int userId;

@Column( name = "device_firmware_id" )
private int deviceFirmware;

@Column( name = "device_hardware_id" )
private int deviceHardware;

@Column( name = "device_make_id" )
private int deviceMake;

@Column( name = "device_model_id" )
private int deviceModel;

@Column( name = "device_template_id" )
private int deviceTemplateId;

@Column( name = "device_type_id" )
private int deviceType;


@ManyToOne( fetch = FetchType.LAZY )
@JoinColumn( name = "system_status_id" )
@Fetch(FetchMode.JOIN)
private StatusDetail systemStatus;

@Column( name = "system_status_id",insertable=false,updatable=false)
private int systemStatusId;

@Column( name = "connection_status_id" )
private int connectionStatus;

@Column( name = "device_param1" )
private String deviceParam1;

@Column( name = "device_param2" )
private String deviceParam2;

@Column( name = "device_param3" )
private String deviceParam3;

@Column( name = "device_param4" )
private String deviceParam4;

@Column( name = "device_param5" )
private String deviceParam5;

@Column( name = "is_disabled", length = 1, columnDefinition = "BIT" )
private boolean isDisabled;

@Column( name = "suppress_alarm", length = 1, columnDefinition = "BIT" )
private boolean suppressAlarm;

@Column( name = "parent_device_id" )
private Integer parentDeviceId;

@Column( name = "datapoint_set_config_id" )
private Integer datapointSetConfigId;

@OneToMany( mappedBy = "device",fetch = FetchType.EAGER)
@Fetch(FetchMode.JOIN)
private List<DeviceProperties> deviceProperties;

@ManyToOne( fetch = FetchType.LAZY )
@JoinColumn( name = "device_template_id", insertable = false, updatable = false )
@Fetch(FetchMode.JOIN)
private DeviceTemplate deviceTemplate;

public Device() {
}

public int getConnectionStatus() {
return connectionStatus;
}

public Date getConnectionStatusUpdateTime() {
return connectionStatusUpdateTime;
}

public Date getCreationTime() {
return creationTime;
}

public int getCustomerId() {
return customerId;
}

public Integer getDatapointSetConfigId() {
return datapointSetConfigId;
}

public String getDescription() {
return description;
}

public int getDeviceFirmware() {
return deviceFirmware;
}

public int getDeviceHardware() {
return deviceHardware;
}

public int getDeviceMake() {
return deviceMake;
}

public int getDeviceModel() {
return deviceModel;
}

public String getDeviceParam1() {
return deviceParam1;
}

public String getDeviceParam2() {
return deviceParam2;
}

public String getDeviceParam3() {
return deviceParam3;
}

public String getDeviceParam4() {
return deviceParam4;
}

public String getDeviceParam5() {
return deviceParam5;
}

public int getDeviceTemplateId() {
return deviceTemplateId;
}

public int getDeviceType() {
return deviceType;
}

public int getIddevice() {
return iddevice;
}

public String getIp() {
return ip;
}

public String getLocation() {
return location;
}

public String getName() {
return name;
}

public Integer getParentDeviceId() {
return parentDeviceId;
}

public int getPort() {
return port;
}

public String getSerialKey() {
return serialKey;
}

public StatusDetail getSystemStatus() {
return systemStatus;
}

public Date getSystemStatusUpdateTime() {
return systemStatusUpdateTime;
}

public int getUserId() {
return userId;
}

public boolean isDisabled() {
return isDisabled;
}

public boolean isSuppressAlarm() {
return suppressAlarm;
}

public void setConnectionStatus(int connectionStatus) {
this.connectionStatus = connectionStatus;
}

public void setConnectionStatusUpdateTime(Date connectionStatusUpdateTime) {
this.connectionStatusUpdateTime = connectionStatusUpdateTime;
}

public void setCreationTime(Date creationTime) {
this.creationTime = creationTime;
}

public void setCustomerId(int cutomerId) {
customerId = cutomerId;
}

public void setDatapointSetConfigId(Integer datapointSetConfigId) {
this.datapointSetConfigId = datapointSetConfigId;
}

public void setDescription(String description) {
this.description = description;
}

public void setDeviceFirmware(int deviceFirmware) {
this.deviceFirmware = deviceFirmware;
}

public void setDeviceHardware(int deviceHardware) {
this.deviceHardware = deviceHardware;
}

public void setDeviceMake(int deviceMake) {
this.deviceMake = deviceMake;
}

public void setDeviceModel(int deviceModel) {
this.deviceModel = deviceModel;
}

public void setDeviceParam1(String deviceParam1) {
this.deviceParam1 = deviceParam1;
}

public void setDeviceParam2(String deviceParam2) {
this.deviceParam2 = deviceParam2;
}

public void setDeviceParam3(String deviceParam3) {
this.deviceParam3 = deviceParam3;
}

public void setDeviceParam4(String deviceParam4) {
this.deviceParam4 = deviceParam4;
}

public void setDeviceParam5(String deviceParam5) {
this.deviceParam5 = deviceParam5;
}

public void setDeviceTemplateId(int deviceTemplateId) {
this.deviceTemplateId = deviceTemplateId;
}

public void setDeviceType(int deviceType) {
this.deviceType = deviceType;
}

public void setDisabled(boolean isDisabled) {
this.isDisabled = isDisabled;
}

public void setIddevice(int iddevice) {
this.iddevice = iddevice;
}

public void setIp(String ip) {
this.ip = ip;
}

public void setLocation(String location) {
this.location = location;
}

public void setName(String name) {
this.name = name;
}

public void setParentDeviceId(Integer parentDeviceId) {
this.parentDeviceId = parentDeviceId;
}

public void setPort(int port) {
this.port = port;
}

public void setSerialKey(String serialKey) {
this.serialKey = serialKey;
}

public void setSuppressAlarm(boolean suppressAlarm) {
this.suppressAlarm = suppressAlarm;
}

public void setSystemStatus(StatusDetail systemStatus) {
this.systemStatus = systemStatus;
}

public void setSystemStatusUpdateTime(Date systemStatusUpdateTime) {
this.systemStatusUpdateTime = systemStatusUpdateTime;
}

public void setUserId(int userId) {
this.userId = userId;
}

public List<DeviceProperties> getDeviceProperties() {
return deviceProperties;
}

public void setDeviceProperties(List<DeviceProperties> deviceProperties) {
this.deviceProperties = deviceProperties;
}

public DeviceTemplate getDeviceTemplate() {
return deviceTemplate;
}

public void setDeviceTemplate(DeviceTemplate deviceTemplate) {
this.deviceTemplate = deviceTemplate;
}


public int getSystemStatusId() {
return systemStatusId;
}

public void setSystemStatusId(int systemStatusId) {
this.systemStatusId = systemStatusId;
}


}


This is the interface declare for supporting polmorphic assosiation



public interface Node {

}


I have enabled OpenEntityFilter for solving Lazy Initialization in Spring



<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://ift.tt/nSRXKP"
xmlns:xsi="http://ift.tt/ra1lAU"
xsi:schemaLocation="http://ift.tt/nSRXKP http://ift.tt/1eWqHMP">
<!-- Dispatcher Servlet -->
<servlet>
<servlet-name>collygo-core-config</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>collygo-core-config</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>

<!-- location of spring xml files -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:collygo-core-config.xml</param-value>
</context-param>
<context-param>
<param-name>contextInitializerClasses</param-name>
<param-value>com.vuelogix.collygo.core.init.CollygoApplicationContextInitializer</param-value>
</context-param>

<!-- the listener that kick-starts Spring -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Try to solve lazy loading -->
<filter>
<filter-name>Spring OpenEntityManagerInViewFilter</filter-name>
<filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
</filter>

<filter-mapping>
<filter-name>Spring OpenEntityManagerInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<!-- Camel servlet -->
<servlet>
<servlet-name>CamelServlet</servlet-name>
<servlet-class>org.apache.camel.component.servlet.CamelHttpTransportServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<!-- Camel servlet mapping -->
<servlet-mapping>
<servlet-name>CamelServlet</servlet-name>
<url-pattern>/camel/*</url-pattern>
</servlet-mapping>

<!--Spring Security Filters -->

</web-app>


Here is my spring config for Data Acess



<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://ift.tt/GArMu6"
xmlns:xsi="http://ift.tt/ra1lAU"
xmlns:p="http://ift.tt/1jdM0fE"
xmlns:tx="http://ift.tt/OGfeU2"
xmlns:context="http://ift.tt/GArMu7"
xmlns:jdbc="http://ift.tt/18IIlo0"
xmlns:jpa="http://ift.tt/1iMF6wA"
xmlns:repository="http://ift.tt/1oHDN8f"
xmlns:util="http://ift.tt/OGfeTW"
xmlns:aop="http://ift.tt/OpNdV1"
xmlns:camel="http://ift.tt/TZ5qsO"
xsi:schemaLocation="http://ift.tt/18IIlo0 http://ift.tt/1b0hqjk
http://ift.tt/GArMu6 http://ift.tt/1jdM0fG
http://ift.tt/GArMu7 http://ift.tt/1jdLYo7
http://ift.tt/OpNdV1 http://ift.tt/1feTlrW
http://ift.tt/1iMF6wA http://ift.tt/1jZdjKs
http://ift.tt/TZ5qsO http://ift.tt/1apCv6i
http://ift.tt/OGfeU2 http://ift.tt/18tm2Tg
http://ift.tt/1oHDN8f http://ift.tt/1oVqiiH
http://ift.tt/OGfeTW http://ift.tt/1feTls0">

<!-- Declare a JPA entityManagerFactory -->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:dataSource-ref="jpaDataSource" p:jpaVendorAdapter-ref="hibernateVendor"
p:packagesToScan="com.vuelogix.collygo.data.entities"
p:jpaProperties-ref="hibernateConfig" p:jpaDialect-ref="jpaDialect"
p:persistenceProvider-ref="hibernatePersistence"
p:persistenceUnitName="entityManagerFactory" />

<!-- Declare a datasource that has pooling capabilities -->
<bean id="jpaDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="${database.driverClassName}" />
<property name="jdbcUrl" value="${database.url}" />
<property name="user" value="${database.username}" />
<property name="password" value="${database.password}" />
<property name="acquireIncrement" value="1" />
<property name="acquireRetryAttempts" value="3" />
<property name="acquireRetryDelay" value="300" />
<property name="initialPoolSize" value="100" />
<property name="maxPoolSize" value="200" />
<property name="minPoolSize" value="1" />
</bean>
<aop:config proxy-target-class="true">
</aop:config>


<aop:aspectj-autoproxy proxy-target-class="true" />
<tx:annotation-driven mode="aspectj" />

<!-- Declare a Hibernate Vendor -->
<bean id="hibernateVendor"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
p:showSql="false" />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
p:entityManagerFactory-ref="entityManagerFactory" />

<!-- Declare a Hibernate Config -->
<util:map id="hibernateConfig">
<entry key="hibernate.hbm2ddl.auto" value="validate" />
<entry key="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
<entry key="hibernate.show_sql" value="false" />
<entry key="hibernate.connection.zeroDateTimeBehavior" value="convertToNull" />
<entry key="hibernate.cache.region.factory_class" value="org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory"/>
<entry key="hibernate.cache.use_second_level_cache" value="true"/>
<entry key="hibernate.cache.use_query_cache" value="true"/>

</util:map>

<!-- Declare a JPA Dialect -->
<bean name="jpaDialect"
class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
<bean id="hibernatePersistence" class="org.hibernate.ejb.HibernatePersistence">
</bean>

<!-- Activate Spring Data JPA repository support -->
<jpa:repositories base-package="com.vuelogix.collygo.data.repository"
entity-manager-factory-ref="entityManagerFactory"
transaction-manager-ref="transactionManager">
<!-- <repository:include-filter type="regex" expression="com.gdev.vim.repository.*"/> -->
</jpa:repositories>
</beans>


I am using spring data . Here is my Repository class



@Repository
public interface DeviceTreeRepository extends CrudRepository<DeviceTree, Integer> {

@Query( "SELECT d FROM DeviceTree d where d.customerId=:customerId AND d.iddeviceTree BETWEEN :left AND :right AND d.isDisabled=false" )
List<DeviceTree> getNodes(@Param( "left" ) int left, @Param( "right" ) int rgt,
@Param( "customerId" ) int customerId);

@Query( "SELECT d FROM DeviceTree d FETCH ALL PROPERTIES where d.customerId=:customerId AND d.isDisabled=false" )
List<DeviceTree> findByCustomerId( @Param( "customerId" )int customerId);



@Query( "SELECT d FROM DeviceTree d where d.customerId=:customerId AND d.nodeType.idnodeType=:nodeType AND d.iddeviceTree BETWEEN :left AND :right AND d.isDisabled=false" )
List<DeviceTree> getNodesforNodeType(@Param( "left" ) int left, @Param( "right" ) int right,
@Param( "nodeType" ) int nodeType, @Param( "customerId" ) int customerId);

@Query( "SELECT d FROM DeviceTree d where d.customerId=:customerId AND d.statusDetail.idstatus=:statuslist AND d.iddeviceTree BETWEEN :left AND :right AND d.isDisabled=false" )
List<DeviceTree> getNodesforStatus(@Param( "left" ) int left, @Param( "right" ) int right,
@Param( "statuslist" ) List<Integer> statuslist,
@Param( "customerId" ) int customerId);


@Query( "SELECT d FROM DeviceTree d where d.customerId=:customerId AND d.nodeType.idnodeType=:nodeTypeId AND d.isDisabled=false")
List<DeviceTree> findByNodeTypeId(@Param( "nodeTypeId" )int nodeTypeId,@Param( "customerId" ) int customerId);

@Query( "SELECT d FROM DeviceTree d where d.customerId=:customerId AND d.nodeType.idnodeType in :nodeTypes AND d.isDisabled=false")
List<DeviceTree> findByNodeType(@Param( "nodeTypes" )List<Integer> nodeTypes,@Param( "customerId" ) int customerId);


}


Aucun commentaire:

Enregistrer un commentaire