2

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.

Koziołek
  • 2,791
  • 1
  • 28
  • 48

1 Answers1

1

In all relationships there is an owning side (atleast in ORM). In your Many-to-One case you have made the Vote as the owning side. That means, it is the dependency of a vote to associate itself with the question. Hence question.addVote(vote1) will not work, but vote.setQuestion(question) will make everything work. The Vote is the owning side, as you have declared the JoinColumn on this side and the mappedBy field on the Question side.

Edit: And you should now persist the vote object and not the question object to have any effect.

Satadru Biswas
  • 1,555
  • 2
  • 13
  • 23