1

i use spring 3.2, spring data and jpa.

i save an Advertisement object, after i save message

i try to access message from Advertisement but it's null

@Entity
public class Advertisement implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@OneToMany(mappedBy="id", cascade={CascadeType.REMOVE}, fetch=FetchType.LAZY)
private Set<Message> messages;
}

@Entity
public class Message implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@ManyToOne
private Advertisement advertisement;
}

test unit

Advertisement ads = new Advertisement();
ads = advertisementRepo.save(ads);

assertNotNull(ads);
assertNotNull(ads.getId());

Message message = new Message();
message.setAdvertisement(ads);
message = msgRepo.save(message);

ads = advertisementRepo.findOne(ads.getId());
ads.getMessages(); //return null

why ads.getMessages() don't return messages?

3 Answers 3

4

The problem is that bidirectional relationships are not transparently managed by JPA. When manipulating one side of a bidirectional relationship, the application has to ensure that the other side is updated accordingly.

This can easily be done by writing setter methods that update the associated entity as well. For example, when setting the Advertisment of a Message, you can add the Message instance to the collection in Advertisment:

@Entity
public class Message implements Serializable {

    ...

    public void setAdvertisement(Advertisement advertisement) {
        this.advertisement = advertisement;
        advertisement.getMessages().add(this);
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

that work but in Advertisement, i need to do: Set<Message> messages = new HashSet<Message>(); before i had: Set<Message> messages;
Sure, you need to initialize the collection, I forgot to mention that.
1

Try to save the Advertisement after you assign it a new Message collection:

Advertisement ads = new Advertisement();
ads = advertisementRepo.save(ads);

assertNotNull(ads);
assertNotNull(ads.getId());

Message message = new Message();
message.setAdvertisement(ads);
ads.setMessages(new HashSet<Message>());
ads.getMessages().add(message);
ads = advertisementRepo.save(ads);
message = msgRepo.save(message);

ads = advertisementRepo.findOne(ads.getId());
ads.getMessages(); //return null

Comments

0

This is returning null because you are saving the non-owning entity first and then the owning entity. If you save message before ads it should return non-null value.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.