I read similar questions, but still have problem.
Configuration info: Hibernate 3.5.1
Parent class Question:
@Entity
public class Question implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="questionId")
private long id;
private String title;
private String description;
@OneToMany(cascade=CascadeType.ALL, mappedBy="question")
private Set<Vote> votes;
public void addVote(Vote vote){
if(votes==null)
votes = new HashSet<Vote>();
getVotes().add(vote);
}
}
Child class Vote:
@Entity
public class Vote implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="voteId")
private long id;
private transient InetAddress address;
@ManyToOne
@JoinColumn(name="questionId")
private Question question;
@Enumerated(EnumType.STRING)
private Mode mode;
// ...
}
And finally very simple test:
@Test
public void testSaveOrUpdate() {
Vote vote1 = new Vote();
vote1.setAddress(InetAddress.getLocalHost());
vote1.setMode(Mode.HIM);
question = new Question();
question.setTitle("test?");
question.setDescription("test");
question.addVote(vote1);
question2 = questionDao.saveOrUpdate(question);
assertNotNull(question2);
Set<Vote> votes = question.getVotes();
assertEquals(votes.size(), 1);
for(Vote vote:votes)
assertNotNull(vote.getQuestion());
}
test fail because vote.getQuestion() return null. When I check in DB there are null in questionId column. My question is what I should do to have reference to question in vote from votes? there is something wrong with mapping but i have no idea what.