I have a problem with OneToMany relations. I'm using spring-mvc and spring-security and hibernate 4.
I'm using annotations for all.
My problem is in the entity War when I see the atributte List players debugging, I see players= PersistentBag
and when I click it com.sun.jdi.InvocationException occurred invoking method.
Also I get this Exceptions:
org.apache.jasper.JasperException: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: clanwar.model.War.players, could not initialize proxy - no Session
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: clanwar.model.War.players, could not initialize proxy - no Session
Entities:
@Entity
@Table(name = "WARS")
public class War implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "ID", nullable = false)
private int id;
@ManyToOne
@JoinColumn(name = "CLAN")
private Clan clan;
@Column(name = "START_DATE")
private Date startDate;
@Column(name = "ENEMY_NAME")
private String enemyName;
@OneToMany(mappedBy = "war")
private List<WarPlayer> players;
@Transient
private List<Enemy> enemies;
public War() { }
// Getters and setters.
}
--
@Entity
@Table(name = "WAR_PLAYERS")
public class WarPlayer implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@ManyToOne
@JoinColumn(name = "WAR")
private War war;
@Id
@ManyToOne
@JoinColumn(name = "PLAYER")
private Player player;
@Column(name = "WAR_NUMBER")
private int warNumber;
@ManyToOne
@JoinColumn(name = "OBJETIVE_1")
private Attack objetive1;
@ManyToOne
@JoinColumn(name = "OBJETIVE_2")
private Attack objetive2;
@ManyToOne
@JoinColumn(name = "RECOMMENDED_1")
private Attack recommended1;
@ManyToOne
@JoinColumn(name = "RECOMMENDED_2")
private Attack recommended2;
@ManyToOne
@JoinColumn(name = "FINAL_1")
private Attack final1;
@ManyToOne
@JoinColumn(name = "FINAL_2")
private Attack final2;
private String comment;
public WarPlayer() {}
// Getters and setters
}
My DAO
@Override
public War findById(int id) throws DaoException {
War war;
try {
war = (War) getSession()
.createQuery("from War where ID = :id")
.setParameter("id", id)
.uniqueResult();
} catch (Exception e) {
throw new DaoException(e.getMessage());
}
return war;
}
Hibernate documentation says:
In the normal case the orders association would be lazy loaded by Hibernate
So, you need to use eager fetching:
@OneToMany(mappedBy = "war",fetch = FetchType.EAGER)
private List<WarPlayer> players;