Many-to-Many - lazily initialization failing on a collection [duplicate] - spring

I have 2 models.
User:
#Entity
public class User implements Serializable {
Long id;
String name;
List<Car> cars;
public User() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Car> getCars() {
return cars;
}
public void setCars(List<Car> cars) {
this.cars = cars;
}
}
Car:
#Entity
public class Car implements Serializable {
Long id;
String mark;
public Car() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getMark() {
return mark;
}
public void setMark(String mark) {
this.mark = mark;
}
}
Mapping fies:
User:
<hibernate-mapping>
<class name="com.bontade.phone_book.mvc.spring.models.User" table="USERS">
<id name="id" type="java.lang.Long">
<column name="ID" />
<generator class="identity" />
</id>
<property name="name" not-null="true" length="100" type="java.lang.String">
<column name="NAME" />
</property>
<list name="cars" table="USER_CAR" cascade="all">
<key>
<column name="USER_ID" />
</key>
<list-index></list-index>
<many-to-many column="CAR_ID" class="com.bontade.phone_book.mvc.spring.models.Car" />
</list>
</class>
</hibernate-mapping>
Car:
<hibernate-mapping>
<class name="com.bontade.phone_book.mvc.spring.models.Car" table="CARS">
<id name="id" type="java.lang.Long">
<column name="ID" />
<generator class="identity" />
</id>
<property name="mark" not-null="true" length="20" type="java.lang.String">
<column name="MARK" />
</property>
</class>
</hibernate-mapping>
HomePageController:
public class HomePageController extends AbstractController {
private UserDAO userDAO;
private CarDAO carDAO;
#Override
protected ModelAndView handleRequestInternal(HttpServletRequest request,
HttpServletResponse response) throws Exception {
Car markCar = new Car();
markCar.setId(null);
markCar.setMark("111");
carDAO.saveCar(markCar);
User mark = new User();
mark.setId(null);
mark.setName("mark");
List a = new ArrayList<Car>();
a.add(markCar);
mark.setCars(a);
userDAO.saveUser(mark);
List<User> users = userDAO.getAll();
System.out.println("==" + users.size() + "===");
System.out.println(users.get(0).getCars().get(0).getMark());
...
}
...
}
But when I executes line :
System.out.println(users.get(0).getCars().get(0).getMark());
I'm getting error with following stack trace:
Hibernate: select user0_.ID as ID0_, user0_.NAME as NAME0_ from USERS user0_
==1==
2011-02-23 17:35:10 org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/PhoneBook] threw exception [Request processing failed; nested exception is org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.bontade.phone_book.mvc.spring.models.User.cars, no session or session was closed] with root cause
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.bontade.phone_book.mvc.spring.models.User.cars, no session or session was closed
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:380)
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:372)
at org.hibernate.collection.AbstractPersistentCollection.readElementByIndex(AbstractPersistentCollection.java:173)
at org.hibernate.collection.PersistentList.get(PersistentList.java:293)
at com.bontade.phone_book.mvc.spring.controllers.HomePageController.handleRequestInternal(HomePageController.java:59)
at org.springframework.web.servlet.mvc.AbstractController.handleRequest(AbstractController.java:153)
at org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:48)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:875)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:807)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:571)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:501)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:306)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:96)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:244)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:108)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:558)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:379)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:243)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:259)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:281)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
Have I wrong constructed mapping files, especially many-to-many relation?

By default Hibernate will lazy load collections. In other words, it won't go to the database to retrieve the list of cars until it absolutely needs to. What that means is the returned object from your dao layer won't have the cars list initialized until you try to access it. When you do try to access it, you're no longer within the session, and so you get the exception.
You can explicitly disable lazy fetching on that list property by setting lazy="false" in the hibernate mapping, which will make sure the entire property is populated before returning from your dao layer.

Related

Error reading 'nom' on type dao.Etudiant_$$_jvst1a2_0 Hibernate

I want to search on a table by ID , the search work fine , but when hibernate don t find any row it s return this error :
Error reading "nom" on type dao.Etudiant , and sometimes it s return : No row with the given identifier exists:[dao.Etudiant#4]
I want to show nothing when hibernate don t find that ID on the table , need your helps thanks , I m stack my learning, I googled a lot without any solution. this is my code :
Controller :
package controller;import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.omg.CORBA.Request;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import dao.DaoEtudiant;
import dao.Etudiant;
import service.EtudiantMetier;
#Controller
public class EtudiantController {
#Autowired
EtudiantMetier service;
#RequestMapping("afficherId")
public String afficheId(Model mod,#RequestParam(value="id") Long id)
{
List <Etudiant> ets1=new ArrayList<Etudiant>();
ets1.add(service.chercheEtudiantID(id));
mod.addAttribute("etudiants",ets1);
return "etudiant1";
}
}
Class : Etudiant :
package dao;
import java.util.Date;
public class Etudiant {
private Long idEtudiant;
private String nom;
private String prenom;
private Date dateNaissance;
private String email;
public Etudiant() {
super();
}
public Long getIdEtudiant() {
return idEtudiant;
}
public void setIdEtudiant(Long idEtudiant) {
this.idEtudiant = idEtudiant;
}
public Etudiant(String nom, String prenom, Date dateNaissance, String email) {
super();
this.nom = nom;
this.prenom = prenom;
this.dateNaissance = dateNaissance;
this.email = email;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public Date getDateNaissance() {
return dateNaissance;
}
public void setDateNaissance(Date dateNaissance) {
this.dateNaissance = dateNaissance;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Etudiant.hbm.xml:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Oct 20, 2016 7:42:26 AM by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping>
<class name="dao.Etudiant" table="etudiant">
<id name="idEtudiant">
<column name="ID_ETUDIANT" />
<generator class="native" />
</id>
<property name="nom" column="NOM" />
<property name="prenom" >
<column name="PRENOM" />
</property>
<property name="dateNaissance" >
<column name="DATE_NAISSANCE" />
</property>
<property name="email" >
<column name="EMAIL" />
</property>
</class>
Hibernate.cfg.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class"> com.mysql.jdbc.Driver</property>
<property
name="connection.url">jdbc:mysql://localhost:3306/etudes</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">100</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop the existing tables and create new one -->
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.enable_lazy_load_no_trans" >
true
</property>
<!-- Mention here all the model classes along with their package name -->
<mapping resource="dao/Etudiant.hbm.xml"/>
</session-factory>
Etudiantmetierimpl.java:
#Override
public Etudiant chercheEtudiantID(Long idEtudiant) {
Session session=HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
System.out.println("avant load session");
Etudiant et=session.load (Etudiant.class, idEtudiant);
//Etudiant et=session.get (Etudiant.class, idEtudiant); // presque meme chose que load
System.out.println("apres load session et ");
session.close();
return et;
}
find it finally. I change this line :
Etudiant et=session.load (Etudiant.class, idEtudiant)
to :
Etudiant et=session.get (Etudiant.class, idEtudiant)
doc:
session.load()
• It will always return a “proxy” (Hibernate term) without hitting the database. In Hibernate, proxy is an object with the given identifier value, its properties are not initialized yet, it just look like a temporary fake object.
• If no row found , it will throws an ObjectNotFoundException.
session.get()
• It always hit the database and return the real object, an object that represent the database row, not proxy.
• If no row found , it return null.

Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'std' defined in file

package com.nareshit.beans;
public class Address {
private String city,state;
public String toString()
{
return "\n city:"+city+"\nstate:"+state;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
}
package com.nareshit.clients;
import java.awt.Container;
import java.beans.Beans;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import com.nareshit.beans.Student;
public class Test {
public static void main(String[] args)
{
BeanFactory factory=new XmlBeanFactory(new ClassPathResource("MyBeans.xml"));
Student std1=(Student)factory.getBean("std");
std1.getStudentDetails();
}
}
package com.nareshit.beans;
public class Student {
private int sid;
private String name;
private String address;
public void getStudentDetails()
{
System.out.println("student id:"+sid);
System.out.println("student name:"+name);
System.out.println("student address:"+address);
}
public int getSid() {
return sid;
}
public void setSid(int sid) {
this.sid = sid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="std" class="com.nareshit.beans.Student">
<property name="std" value="1001"/>
<property name="name" value="mitu"/>
<property name="address" ref="addressObj"/>
</bean>
<bean id="addressObj" class="com.nareshit.beans.Address">
<property name="city" value="bam"/>
<property name="state" value="odisha"/>
</bean>
</beans>
This is the spring setter injection prog. where i am getting error:
Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'std' defined in file("")
how to solve it?
Please see com.nareshit.beans.Student class. It is having one property named as address which is a type of String. When you are writing the XML,
you are giving one reference type of com.nareshit.beans.Address.
Solution :
1. You can give a String value in the XML for address property.like
ddress property like
<bean id="std" class="com.nareshit.beans.Student">
<property name="std" value="1001"/>
<property name="name" value="mitu"/>
<property name="address" value="SOME ADDRESS"/>
</bean>
2. You can change the type of address property in Student Class like
public class Student{
Address address;
//declaration of rest property
//Some Boiler Plate Code
}

Hibernate Oracle Create table

I have a problem while creating table in oracle via hibernate.
I get these two error:
Could not execute JDBC batch update
and
ORA-00942: table or view does not exist
This is my hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:#localhost:1521:ORCL</property>
<property name="hibernate.connection.username">system</property>
<property name="hibernate.connection.password">mypass</property>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
<property name="hibernate.default_schema">SamTest</property>
<property name="hibernate.connection.pool_size">5</property>
<property name="show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping class="com.sam.Teacher" />
</session-factory>
</hibernate-configuration>
Teacher entity
#Table(schema="SamTest")
public class Teacher {
#Id
//#GenericGenerator(name = "generator", strategy = "increment")
private int teacher_Id;
#Column
private int teacher_No;
#Column
private String teacher_Name;
#Column
private String teacher_Surname;
#Column
private String department;
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public int getTeacher_Id() {
return teacher_Id;
}
public void setTeacher_Id(int teacher_Id) {
this.teacher_Id = teacher_Id;
}
public int getTeacher_No() {
return teacher_No;
}
public void setTeacher_No(int teacher_No) {
this.teacher_No = teacher_No;
}
public String getTeacher_Name() {
return teacher_Name;
}
public void setTeacher_Name(String teacher_Name) {
this.teacher_Name = teacher_Name;
}
public String getTeacher_Surname() {
return teacher_Surname;
}
public void setTeacher_Surname(String teacher_Surname) {
this.teacher_Surname = teacher_Surname;
}
public Teacher() {
}
public Teacher(int teacher_No, String teacher_Name, String teacher_Surname, String department) {
this.teacher_No = teacher_No;
this.teacher_Name = teacher_Name;
this.teacher_Surname = teacher_Surname;
this.department=department;
}
}
Exception
Exception in thread "main" org.hibernate.exception.SQLGrammarException: Could not execute JDBC batch update
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:92)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:275)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:268)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:184)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1216)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:383)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:133)
at com.sam.RunHiber.main(RunHiber.java:23)
Caused by: java.sql.BatchUpdateException: ORA-00942: table or view does not exist
at oracle.jdbc.driver.OraclePreparedStatement.executeBatch(OraclePreparedStatement.java:10500)
at oracle.jdbc.driver.OracleStatementWrapper.executeBatch(OracleStatementWrapper.java:230)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268)
... 8 more
It appears you're creating getters and setters in Hibernate, but I'm pretty sure you're not creating a table. This is only the reference to an Oracle table that obviously does not exist (yet). Hence the error "Table or view does not exists".

Autowiring String property through application context

I want to autowire a String bean as below
<bean id="name" class="java.lang.String" autowire="byName">
<constructor-arg value="Aravind"/>
</bean>
<bean id="employee" class="Employee" autowire="byName"/>
public Class Employee
{
private String name;
public void setName(String name)
{
this.name=name;
}
public String getName()
{
return name;
}
}
When I try to access the name attribute in the employee is null
Employee emp=(Employee)getApplicationContext().getBean("employee");
System.out.println(emp.getName()==null);
It prints true.
Can someone help on this?
You still need to set the property on the Employee somehow.
Setting the name can be done in multiple ways.
XML configuration.
<bean id="employee" class="Employee" autowire="byName">
<property name="name">
<ref bean="name" />
</property>
</bean>
Using #Autowired
public Class Employee {
#Autowired
private String name;
public void setName(String name) {
this.name=name;
}
public String getName() {
return name;
}
}

Hibernate not seeing a getter method

For some reason Hibernate is not seeing a Getter in one of my classes, or at least that's what I think is happening. Is there something I have set wrong in my hibernate mapping file or a different XML configuration file?
The code I am showing you is generated by WaveMaker and is supposed to work. I am trying to run a simple HQL query but I always get the following error. It doesn't matter how simple the query is or on what entities I query, I always get the "Could not find a getter" error.
I am using WaveMaker 6.5 with whatever version of Hibernate and Spring it downloads during installation.
Here is the error I get:
Run query error: Error creating bean with name 'm2mex2DBDataService' defined in
resource loaded through SAX InputSource: Cannot resolve reference to bean
'm2mex2DBHibernateTemplate' while setting constructor argument; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating bean with name
'm2mex2DBHibernateTemplate' defined in resource loaded through SAX InputSource: Cannot
resolve reference to bean 'm2mex2DBSessionFactory' while setting bean property
'sessionFactory'; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating bean with name
'm2mex2DBSessionFactory' defined in resource loaded through SAX InputSource: Invocation
of init method failed; nested exception is org.hibernate.PropertyNotFoundException:
Could not find a getter for bookauthors in class com.m2mex2db.data.Author
Here is the code of my Author class:
package com.m2mex2db.data;
import java.util.HashSet;
import java.util.Set;
/**
* m2mex2DB.Author
* 05/08/2013 16:33:50
*
*/
public class Author {
private Integer id;
private String firstname;
private String lastname;
private Set<com.m2mex2db.data.Bookauthor> bookauthors = new HashSet<com.m2mex2db.data.Bookauthor>();
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public Set<com.m2mex2db.data.Bookauthor> getBookauthors() {
return bookauthors;
}
public void setBookauthors(Set<com.m2mex2db.data.Bookauthor> bookauthors) {
this.bookauthors = bookauthors;
}
}
and here is my Hibernate mapping file:
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.m2mex2db.data.Author" table="author" schema="kentoj" dynamic-insert="false" dynamic-update="false">
<id name="id" type="integer">
<column name="id"/>
<generator class="assigned"/>
</id>
<property name="firstname" type="string">
<column name="firstname" length="98" not-null="true"/>
</property>
<property name="lastname" type="string">
<column name="lastname" length="98"/>
</property>
<set name="bookauthors" inverse="true" cascade="">
<key>
<column name="authorid" not-null="true"/>
</key>
<one-to-many class="com.m2mex2db.data.Bookauthor"/>
</set>
</class>
</hibernate-mapping>
http://forum.springsource.org/showthread.php?29965-PropertyNotFoundException-getter
Hibernate - PropertyNotFoundException: Could not find a getter for

Resources