views:

92

answers:

1

I'm still learning how to set up these mappings using the JPA annotations so this may be a beginner mistake.

I have a User class and a Course class. In the database each Course has a User foreign key in each row (think of the User as the teacher teaching the Course). So each User can have multiple Courses, but each Course has only one User.

In mapping these classes I have written the following code below:

@Entity
public class User extends BaseModel {

 @OneToMany(mappedBy="course")
 private Collection<Course> courses;

 public void setCourses(Collection<Course> courses) { this.courses = courses; }

 public Collection<Course> getCourses() { return courses; }

}

@Entity
public class Course extends BaseModel {

 @ManyToOne
 @JoinColumn(name="user_id")
 private User user;

 public void setUser(User user) { this.user = user; }

 public User getUser() { return user; }

}

I have omitted the irrelevant fields and the BaseModel just accounts for the primary key in each table. Is there anything that is blatantly wrong here? If not what would be a good way to go about debugging a problem like this.

I am receiving a NullPointerException when I try to call a select on the user table. However, when I take out the references to the Course class in the User class everything works perfectly fine.

The line in question is in my DAO class. Perhaps the Entity Manager is failing to initialize. Here's the code.

Query query = Stripersist.getEntityManager().createQuery(getQuery(fieldName, null)).setParameter(fieldName, value);

createQuery() just returns:

String query = "FROM " + entityClass.getName() + " t WHERE t." + fieldName + " = :" + fieldName;

I am using the Stripes framework, Hibernate, and Stripersist if that provides any further clues as to what is wrong.

+1  A: 

From the very first glance, it seems to be that you should write:

@OneToMany(mappedBy="user") 
private Collection<Course> courses; 

I. e. in @OneToMany mappedBy should point to the field which points to the current object.

axtavt