Hi,
I'm new in hibernate and unfortunately I don't manage to make the cascade mode work in my case even if the need is really simple.
Here is my code :
User :
Code:
@Entity
@Table(name="user_t")
public class User implements Serializable {
@Id
@Column(name="id")
@GeneratedValue(strategy=GenerationType.AUTO)
private long id;
@OneToMany(mappedBy="user",cascade=CascadeType.ALL,fetch=FetchType.LAZY)
private List<CatalogAccount> catalogAccounts;
public User() {
id = 0L;
catalogAccounts = new ArrayList<CatalogAccount>();
}
public List<CatalogAccount> getCatalogAccounts() {
return this.catalogAccounts;
}
public void setCatalogAccounts(List<CatalogAccount> pCatalogAccounts) {
this.catalogAccounts = pCatalogAccounts;
}
public void addCatalogAccount(CatalogAccount catalogAccount) {
if ((catalogAccount != null) && (!this.catalogAccounts.contains(catalogAccount))) {
this.catalogAccounts.add(catalogAccount);
}
}
}
CatalogAccount :
Code:
@Entity
@Table(name="catalogaccount_t")
@Inheritance(strategy=InheritanceType.JOINED)
public class CatalogAccount implements Serializable {
@Id
@Column(name="id")
@GeneratedValue(strategy=GenerationType.AUTO)
private long id;
@ManyToOne
@JoinColumn(name="id",nullable=false)
private User user;
public CatalogAccount() {
id = 0L;
this.setUser(null);
}
public long getId() {
return id;
}
public void setId(long pId) {
id = pId;
}
public User getUser() {
return user;
}
public void setUser(User user) {
if ((this.user != null) && (this.user != user)){
this.user.removeCatalogAccount(this);
}
this.user = user;
if (user != null) {
user.addCatalogAccount(this);
}
}
}
Test code :
Code:
emf = Persistence.createEntityManagerFactory("sample");
em = emf.createEntityManager();
User lUser = new User();
CatalogAccount lAccount = new CatalogAccount();
lUser.addCatalogAccount(lAccount);
System.out.println("<<<<<<<<<<<<<<<<<< Trace");
em.getTransaction().begin();
em.persist(lUser);
em.getTransaction().commit();
System.out.println(">>>>>>>>>>>>>>>>>>");
Execution :
Code:
<<<<<<<<<<<<<<<<<< Trace
Hibernate: insert into user_t (login, password) values (?, ?)
>>>>>>>>>>>>>>>>>>
The 'User' instance is persisted but not the included 'CatalogAccount' one... :-(
Thanks !