Hi everyone,
I'm working on a project and realize must be a bidirectional OneToMany relationship with Hibernate JPA.
So I have a user which can have multiple address and a multiple address belonging to a user. So a 1 (user) to n (User Address).
The user address data and the ID of the current user must be stored in the table "user address".
I have the following problem:
If I save the address data of the user in the table "user address" and created in table "Users" a new line containing the empty attributes. That is, the data is not stored, and the correct ID of the current user.
Here are the code:
In User.java:
Code:
...
@Entity
@Table(name="Users")
@SequenceGenerator(name="user_gen", sequenceName="user_id_seq")
public class User implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY, generator="user_gen")
private int userID;
...
//bi-directional many-to-one association to Useraddress
@OneToMany(mappedBy="user", fetch=FetchType.EAGER, cascade = { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE})
private Set<Useraddress> useraddresses = new HashSet<Useraddress>();
...
public void addUseraddress(Useraddress useraddress) {
useraddress.setUser(this);
useraddresses.add(useraddress);
}
...
// Setter and Getter
...
}
In Useraddress.java:
Code:
...
@Entity
@Table(name="UserAddresses")
@SequenceGenerator(name="useraddresses_gen", sequenceName="useraddresses_id_seq")
public class Useraddress implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY, generator="useraddresses_gen")
private int addressID;
...
//bi-directional many-to-one association to User
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name="userID")
private User user;
// Getter and Setter
...
}
The Model:
Code:
...
@Service("userService")
@Repository
public class UserServiceImpl implements UserService {
...
private EntityManager em;
@PersistenceContext
public void setEntityManager(EntityManager em) { this.em = em; }
public EntityManager getEntityManager() { return em; }
@Transactional(readOnly = true)
public void persistUseraddress(Useraddress useraddress) {
// TODO Auto-generated method stub
useraddress = new Useraddress();
User user = new User();
user.addUseraddress(useraddress);
em.persist(useraddress);
}
...
}
Seeking a solution for three days, but in vain.
Can someone please help me here?
Thank you for your help.