christoph123
Grünschnabel
Hallo,
Ich arbeite derzeit an meinem Maturaprojekt. Es handelt sich um eine Hotelsoftware, welche mit dem Springframework und Hibernate arbeitet. Leider bekomme ich beim Laden einer lazy-Beziehung die LazyInitializationException.
Will ich zum Beispiel auf die Nationaltität eines Gasts zugreifen erhalte ich folgenden Fehler:
Die Objekte sehen so aus:
Guest
Nationality
Dazu habe ich DAO Klassen, die mein GenericHibernateDAO implementieren.
GenericHibernateDAO
GuestDAO
Bis jetzt habe ich das LazyProblem durch
SessionFactoryUtils.initDeferredClose(getHibernateTemplate().getSessionFactory());
gelöst, doch leider treten (ich vermute) durch die offenen Sessions im laufe des Programms neue Fehler auf.
Ich arbeite derzeit an meinem Maturaprojekt. Es handelt sich um eine Hotelsoftware, welche mit dem Springframework und Hibernate arbeitet. Leider bekomme ich beim Laden einer lazy-Beziehung die LazyInitializationException.
Will ich zum Beispiel auf die Nationaltität eines Gasts zugreifen erhalte ich folgenden Fehler:
Code:
Client: d518b4aa53374c08:7bd64b0e:120422da103:-7fff is ready
Exception in thread "main" org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:86)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:140)
at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:190)
at at.openhotel.model.object.Nationality_$$_javassist_8.getName(Nationality_$$_javassist_8.java)
Die Objekte sehen so aus:
Guest
Code:
package at.openhotel.model.object;
// Generated 10.01.2009 14:15:38 by Hibernate Tools 3.2.4.CR1
import static javax.persistence.GenerationType.IDENTITY;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* this class represents a guest, it includes personal information referring to
* the guest as well as the list of newsletters the guest got, if he is a regular
* or on the black list and if he gets any price reduce.
*/
@Entity
@Table(name = "guest")
public class Guest implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private Nationality nationality;
private Zip zip;
private String firstName;
private String lastName;
private String gender;
private Date dateOfBirth;
private String job;
private String address;
private boolean blacklist;
private String email;
private String phone;
private String title;
private boolean newsletter;
private String comment;
private Double priceReduction;
private boolean isRegular;
private String salutation;
private boolean vegetarian;
private List<Newsletter> newsletters = new ArrayList<Newsletter>(0);
private List<Affinity> affinities = new ArrayList<Affinity>(0);
private List<ContactPerson> contactpersons = new ArrayList<ContactPerson>(0);
private List<Reservation> reservations = new ArrayList<Reservation>(0);
/**
* default constructor
*/
public Guest() {
}
/**
* not preferred constructor
* @param nationality
* @param zip
* @param address
*/
public Guest(Nationality nationality, Zip zip, String address) {
this.nationality = nationality;
this.zip = zip;
this.address = address;
}
/**
* preferred very tiny constructor
* @param firstName first name
* @param lastName last name
* @param gender gender ("m"/"f")
* @param email email address
* @param title title
* @param newsletter if the guest wants to get a newsletter from the hotel
* @param comment space for comments
*/
public Guest(String firstName, String lastName, String gender, String email, String title, boolean newsletter, String comment) {
this.zip = zip;
this.firstName = firstName;
this.lastName = lastName;
this.gender = gender;
this.email = email;
this.title = title;
this.newsletter = newsletter;
this.comment = comment;
}
/**
* extremly detailed constructor
* @param nationality nationality of the guest
* @param zip zip code of the guests domicile
* @param firstName first name
* @param lastName last name
* @param gender gender either m or f
* @param dateOfBirth date of birth to determine the age
* @param job job
* @param address address
* @param blacklist if the guest is welcomed or not
* @param email email address
* @param phone phone number
* @param title title
* @param newsletter if the guest wants to get a newsletter
* @param comment space for comments
* @param priceReduction amount of price reduction for the guest (optional, e.g. for regulars)
* @param isRegular boolean if regular or not
* @param salutation maybe important for sending letters.
*/
public Guest(String firstName, String lastName, String gender, Date dateOfBirth, String job, String address, Nationality nationality, Zip zip, boolean blacklist, String email, String phone, String title, boolean newsletter, String comment, Double priceReduction, boolean isRegular, String salutation) {
this.nationality = nationality;
this.zip = zip;
this.firstName = firstName;
this.lastName = lastName;
this.gender = gender;
this.dateOfBirth = dateOfBirth;
this.job = job;
this.address = address;
this.blacklist = blacklist;
this.email = email;
this.phone = phone;
this.title = title;
this.newsletter = newsletter;
this.comment = comment;
this.priceReduction = priceReduction;
this.isRegular = isRegular;
this.salutation = salutation;
}
/**
* detailed preferred constructor
* @param nationality nationality of the guest
* @param zip zip code of the guests domicile
* @param firstName first name
* @param lastName last name
* @param gender gender either "m" or "f"
* @param address address-field e.g. Mainstreet 12/34
* @param blacklist if the guest is welcomed or not
* @param email email address
* @param phone phone number as a String
* @param title title of the guest
* @param newsletter if the guest wants to get a newsletter
* @param comment space for comments
* @param priceReduction price reduction (optionally, e.g. for regulars)
* @param isRegular if the guest is a regular
* @param salutation salutation e.g. Mr., Ms.,...
*/
public Guest(String firstName, String lastName, String gender, String address, Nationality nationality, Zip zip, boolean blacklist, String email, String phone, String title, boolean newsletter, String comment, Double priceReduction, boolean isRegular, String salutation) {
this.nationality = nationality;
this.zip = zip;
this.firstName = firstName;
this.lastName = lastName;
this.gender = gender;
this.address = address;
this.blacklist = blacklist;
this.email = email;
this.phone = phone;
this.title = title;
this.newsletter = newsletter;
this.comment = comment;
this.priceReduction = priceReduction;
this.isRegular = isRegular;
this.salutation = salutation;
}
/**
* to be used by Java Hibernate
* @param nationality
* @param zip
* @param firstName
* @param lastName
* @param gender
* @param dateOfBirth
* @param job
* @param address
* @param blacklist
* @param email
* @param phone
* @param title
* @param newsletter
* @param comment
* @param priceReduction
* @param isRegular
* @param salutation
* @param newsletters
* @param affinities
* @param contactpersons
* @param reservations
*/
public Guest(Nationality nationality, Zip zip, String firstName,
String lastName, String gender, Date dateOfBirth, String job,
String address, boolean blacklist, String email, String phone,
String title, boolean newsletter, String comment,
Double priceReduction, boolean isRegular, String salutation,
boolean vegetarian,
List<Newsletter> newsletters,
List<Affinity> affinities, List<ContactPerson> contactpersons,
List<Reservation> reservations) {
this.nationality = nationality;
this.zip = zip;
this.firstName = firstName;
this.lastName = lastName;
this.gender = gender;
this.dateOfBirth = dateOfBirth;
this.job = job;
this.address = address;
this.blacklist = blacklist;
this.email = email;
this.phone = phone;
this.title = title;
this.newsletter = newsletter;
this.comment = comment;
this.priceReduction = priceReduction;
this.isRegular = isRegular;
this.salutation = salutation;
this.newsletters = newsletters;
this.vegetarian = vegetarian;
this.affinities = affinities;
this.contactpersons = contactpersons;
this.reservations = reservations;
}
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "nationalityID", nullable = true)
public Nationality getNationality() {
return this.nationality;
}
public void setNationality(Nationality nationality) {
this.nationality = nationality;
}
/*public String getNationalityName() {
if (this.nationality == null)
return "?";
return this.nationality.getName();
}*/
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "zipID", nullable = true)
public Zip getZip() {
return this.zip;
}
public void setZip(Zip zip) {
this.zip = zip;
}
@Column(name = "firstName", length = 30)
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
@Column(name = "lastName", length = 30)
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Column(name = "gender", length = 1)
public String getGender() {
return this.gender;
}
public void setGender(String gender) {
this.gender = gender;
}
@Temporal(TemporalType.DATE)
@Column(name = "dateOfBirth", length = 10)
public Date getDateOfBirth() {
return this.dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
@Column(name = "job", length = 30)
public String getJob() {
return this.job;
}
public void setJob(String job) {
this.job = job;
}
@Column(name = "address", nullable = true, length = 65535)
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
@Column(name = "blacklist")
public boolean getBlacklist() {
return this.blacklist;
}
public void setBlacklist(boolean blacklist) {
this.blacklist = blacklist;
}
@Column(name = "email", length = 200)
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
@Column(name = "phone", length = 30)
public String getPhone() {
return this.phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Column(name = "title", length = 30)
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
@Column(name = "newsletter")
public boolean getNewsletter() {
return this.newsletter;
}
public void setNewsletter(boolean newsletter) {
this.newsletter = newsletter;
}
@Column(name = "comment", length = 65535)
public String getComment() {
return this.comment;
}
public void setComment(String comment) {
this.comment = comment;
}
@Column(name = "priceReduction", precision = 22, scale = 0)
public Double getPriceReduction() {
return this.priceReduction;
}
public void setPriceReduction(Double priceReduction) {
this.priceReduction = priceReduction;
}
@Column(name = "isRegular")
public boolean getIsRegular() {
return this.isRegular;
}
public void setIsRegular(boolean isRegular) {
this.isRegular = isRegular;
}
@Column(name = "salutation", length = 50)
public String getSalutation() {
return this.salutation;
}
public void setSalutation(String salutation) {
this.salutation = salutation;
}
@Column(name = "vegetarian")
public boolean getVegetarian() {
return this.vegetarian;
}
public void setVegetarian(boolean vegetarian) {
this.vegetarian = vegetarian;
}
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinTable(name = "newsletter_has_guest", joinColumns = { @JoinColumn(name = "guestID", nullable = false, updatable = false) }, inverseJoinColumns = { @JoinColumn(name = "newsletterID", nullable = false, updatable = false) })
public List<Newsletter> getNewsletters() {
return this.newsletters;
}
public void setNewsletters(List<Newsletter> newsletters) {
this.newsletters = newsletters;
}
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinTable(name = "guest_has_affinity", joinColumns = { @JoinColumn(name = "guestID", nullable = false, updatable = false) }, inverseJoinColumns = { @JoinColumn(name = "affinityID", nullable = false, updatable = false) })
public List<Affinity> getAffinities() {
return this.affinities;
}
public void setAffinities(List<Affinity> affinities) {
this.affinities = affinities;
}
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "guest")
public List<ContactPerson> getContactpersons() {
return this.contactpersons;
}
public void setContactpersons(List<ContactPerson> contactpersons) {
this.contactpersons = contactpersons;
}
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinTable(name = "reservation_has_guest", joinColumns = { @JoinColumn(name = "guestID", nullable = false, updatable = false) }, inverseJoinColumns = { @JoinColumn(name = "reservationID", nullable = false, updatable = false) })
public List<Reservation> getReservations() {
return this.reservations;
}
public void setReservations(List<Reservation> reservations) {
this.reservations = reservations;
}
}
Nationality
Code:
package at.openhotel.model.object;
// Generated 10.01.2009 14:15:38 by Hibernate Tools 3.2.4.CR1
import static javax.persistence.GenerationType.IDENTITY;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/**
* this class represents the nationaltity of guests, e.g. some guy from Austria=Austrian
*/
@Entity
@Table(name = "nationality")
public class Nationality implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private Country country;
private String name;
private List<Guest> guests = new ArrayList<Guest>(0);
public Nationality() {
}
public Nationality(Country country) {
this.country = country;
}
/**
* preferred constructor
* @param country country the nationality is referring to.
* @param name name of the nationality
*/
public Nationality(Country country, String name) {
this.country = country;
this.name = name;
}
/**
* to be used by Java Hibernate
* @param country
* @param name
* @param guests
*/
public Nationality(Country country, String name, List<Guest> guests) {
this.country = country;
this.name = name;
this.guests = guests;
}
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "countryID", nullable = false)
public Country getCountry() {
return this.country;
}
public void setCountry(Country country) {
this.country = country;
}
@Column(name = "name", length = 30)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "nationality")
public List<Guest> getGuests() {
return this.guests;
}
public void setGuests(List<Guest> guests) {
this.guests = guests;
}
}
Dazu habe ich DAO Klassen, die mein GenericHibernateDAO implementieren.
GenericHibernateDAO
Code:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package at.openhotel.dao;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
/**
* @author Christoph
*/
public class GenericHibernateDAO<T, ID extends Serializable> extends HibernateDaoSupport
implements GenericDAO <T, ID>
{
private Class <T> cEntityClass = null;
@SuppressWarnings("unchecked")
public GenericHibernateDAO ( )
{
this.cEntityClass = ( Class <T> )( ( ParameterizedType ) this.getClass ( ).getGenericSuperclass ( ) ).getActualTypeArguments ( )[0];
}
/**
* ensures that the session is kept for lazy laoding
*/
public void keepSessionOpen ( boolean keepSessionOpen ) {
if(keepSessionOpen) {
getHibernateTemplate().setAllowCreate(false);
SessionFactoryUtils.initDeferredClose(getHibernateTemplate().getSessionFactory());
}
}
@Override
public List<T> loadAll ( boolean keepSessionOpen )
{
keepSessionOpen(keepSessionOpen);
return getHibernateTemplate().loadAll(this.cEntityClass);
}
@Override
public T loadByID(ID id, boolean keepSessionOpen) {
keepSessionOpen(keepSessionOpen);
return (T) getHibernateTemplate().get(this.cEntityClass, id);
}
@Override
public void persist(T entity) {
getHibernateTemplate().save(entity);
// getHibernateTemplate().flush();
}
@Override
public void update(T entity) {
getHibernateTemplate().merge(entity);
getHibernateTemplate().flush();
}
@Override
public void remove(T entity) {
getHibernateTemplate().delete(entity);
getHibernateTemplate().flush();
}
@SuppressWarnings("unchecked")
public List<T> findByCriteria (boolean keepSessionOpen, Criterion... cCriteriaList )
{
keepSessionOpen(keepSessionOpen);
Criteria cCritObj = getHibernateSession().createCriteria ( this.cEntityClass );
for ( Criterion c : cCriteriaList ) {
cCritObj.add ( c );
}
List<T> lReturnValue = cCritObj.list ( );
return lReturnValue;
}
@SuppressWarnings("unchecked")
public List<T> findByDetachedCriteria ( DetachedCriteria detached, boolean keepSessionOpen )
{
keepSessionOpen(keepSessionOpen);
return getHibernateTemplate().findByCriteria(detached);
}
private Session getHibernateSession() {
return (Session)getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
if(session !=null && session.isOpen())
return session;
return null;
}
});
}
}
GuestDAO
Code:
package at.openhotel.dao;
import at.openhotel.model.object.Guest;
/**
* @author Christoph
*/
public class GuestDAO extends GenericHibernateDAO <Guest, Integer>
{
}
Bis jetzt habe ich das LazyProblem durch
SessionFactoryUtils.initDeferredClose(getHibernateTemplate().getSessionFactory());
gelöst, doch leider treten (ich vermute) durch die offenen Sessions im laufe des Programms neue Fehler auf.