Hi everyone,
I have to JPA Hibernate a 1-n relationship to the databank.
The relationship consists of a "user ", the number of "addresses" has.
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", cascade = { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE})
private Set<Useraddress> useraddresses = new HashSet<Useraddress>();
//Konstruktor
public Set<Useraddress> getUseraddresses() {
return this.useraddresses;
}
public void setUseraddresses(Set<Useraddress> useraddresses) {
this.useraddresses = useraddresses;
}
...
}
In useradress.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;
private String city;
private String postcode;
private String street;
// Getter und Setter
//bi-directional many-to-one association to User
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name="userID")
private User user;
...
}
And the model looks like this:
Code:
...
/**
* Saves address to person.
*/
public void saveUseraddress(User user, Useraddress useraddress) {
// UserId zuweisen
int currentuserId = user.getUserID();
User _user = new User(currentuserId);
if (_user.getUseraddresses().contains(useraddress)) {
_user.getUseraddresses().remove(useraddress);
}
_user.getUseraddresses().add(useraddress);
em.persist(useraddress);
return;
}
The address data (city, street, postal code) and the ID of the user must be stored in the User Address table.
Now I do not know why the model code works.
Does anyone here have a tip?
Thank you in advance for your help.