Java JPA class association, NullPointerException?
<p>I'm currently improving an old project that is working fine, I don't have to modify the code nor the database, all I can do is build the correct mapping for it...</p>

<p>There's the Actor, Role and Movie classes... With 3 respective tables in the database :</p>

<p>Table 'Actor' :</p>

<pre><code>`id` INT
`name` VARCHAR
</code></pre>

<p>Table 'Role' :</p>

<pre><code>`film` INT
`actor` INT
`role` VARCHAR
PRIMARY KEY (film, actor, role)
FOREIGN KEY (film) REFERENCES film(id)
</code></pre>

<p>Table 'Movie' :</p>

<pre><code>`id` INT
`title` VARCHAR
</code></pre>

<p>So there are two associations to be made, [ONE actor has ONE role in ONE movie], and [ONE movie contains MANY roles associated to their respectives actors].</p>

<p>And basically, there should be a method in Movie class that allows to create a new role associated to an actor</p>

<pre><code>film.createRole(actor, "Role"); //returning a role
</code></pre>

<p>I'm getting all the time the same error : Java NullPointerException from Hibernate. I guess there's a misconception in my code, any idea how I can do the correct mapping?</p>

<p>Code :</p>

<p>Movie.java :</p>

<pre><code>@Entity
@Table(name = "movie")
public class Movie implements Serializable
{
@Id
@GeneratedValue
private int id;
private String title;

@OneToMany
@JoinTable(name = "role",
joinColumns = {
@JoinColumn(name="role")
}
)
private List&lt;Role&gt; roles;

//Getters and setters

public Role createRole(Actor actor, String role)
{
Role myRole = new Role();
RoleId roleId = new RoleId();
roleId.setMovie(this.id);
roleId.setRole(role);
roleId.setActor(actor.getId());
myRole.setId(roleId);
return myRole;
}
}
</code></pre>

<p>Role.java :</p>

<pre><code>@Entity
@Table(name = "role")
public class Role implements Serializable
{
@EmbeddedId
private RoleId roleId;

//Getters and setters
}
</code></pre>

<p>RoleId.java :</p>

<pre><code>@Embeddable
public class RoleId implements Serializable
{

@ManyToOne(optional=true)
@JoinTable(name = "role", joinColumns = {
@JoinColumn(name="movie")})
private int movie;

@ManyToOne(optional=true)
@JoinTable(name = "role", joinColumns = {
@JoinColumn(name="actor")
})
private int actor;

private String role;

//Getters and setters
}
</code></pre>

<p>Actor.java :</p>

<pre><code>@Entity
@Table(name = "actor")
public class Actor implements Serializable
{
@Id
@GeneratedValue
private int id;
private String name;


@OneToMany
@JoinTable(name = "role", joinColumns = {
@JoinColumn(name="role", unique = true) })
private List&lt;Role&gt; roles;

//Getters and setters

}
</code></pre>

<p>Where's the mistake then?
Thanks.</p>
