Tagebuch eines Technikers

Monday, May 19, 2008

By-directional one-to-many relations with Hibernate and annotations

If have a POJO User and Home. One user can have multiple homes, and homes should know their user. Thus, one user should have many homes, and homes have one owner. Since I ran into some trouble while doing this, this is a short example of what to do. Another simple example (in German) helped me to come to a correct solution

My POJOs look like:
If have a POJO User and Home. One user can have multiple homes, and homes should know their user. Thus, one user should have many homes, and homes have one owner. Since I ran into some trouble while doing this, this is a short example of what to do. Another simple example (in German) helped me to come to a correct solution

My POJOs look like:

@Entity
@Table(name=\"app_user\")
public class User implements Serializable {

private Long id;

private Set<Home> homes = new HashSet<Home>();

/**
* Default constructor - creates a new instance with no values set.
*/
public User() {}

@Id @GeneratedValue(strategy=GenerationType.AUTO)
public Long getId() {
return id;
}

@OneToMany(mappedBy=\"owner\")
public Set<Home> getHomes()
{
return homes;
}

// setters, ...
}
and
@Entity @Table(name=\"home\")
public class Home extends BaseObject {

private Long id;


private User owner;


@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() {
return id;
}

@ManyToOne
@JoinColumn(name=\"user_id\")
public User getOwner() {
return owner;
}

// setters, ...
}
The relationship is saved in Home in the property owner (Home.owner). The foreign key is saved in the field user_id of table home.

When you get the error
mappedBy reference an unknown target
this means that the mappedBy is not set correctly. Ensure that the target is set correctly -- in this scenario, mappedBy specifies field owner of class Home as target.

No comments: