Removing from a table using the @OneToOne annotation

I am using the implementation of JPA2 and Hibernate.

I have a simple mapping:

@Entity 
class Topic {

    @Id
    @GeneratedValue(strategy = IDENTITY)

    int id;

   @OneToOne(cascade = ALL)
   @JoinColumn(name = "id_poll")
   private Poll poll;

}

@Entity 
class Poll {
    @Id
    @GeneratedValue(strategy = IDENTITY)
    int id;
}

Now, when I delete the Poll object, which is also in the subject, I get an error message.

java.sql.SQLException: violation of integrity constraints FKCC42D924982D3F4B table: TOPICS in the instructions [delete from polls, where id =?]

I understand that this is because I cannot delete the survey entry if it has links in another table. How can I solve this problem? Should I manually set poll = null in the Topic table or is there a better solution?

+5
source share
4 answers

This is the expected behavior:

, . JPA, Java , .

: ,

@PreRemove:

@Entity 
class Poll {

    ...

    @PreRemove
    private void preRemove() {
        Poll poll = topic.getPoll();
        topic.setPoll( null );
    }
}

. : JPA/Hibernate ON ON DELETE SET NULL

+5

, @OneToOne JPA 2 orphanRemoval, , .

+1

, Poll Topic, null.

Topic topic = entityManager.find( Topic.class, 1 );
Poll poll = topic.getPoll();
topic.setPoll( null );
entityManager.remove( poll );

.

+1

, Auto-Generated ID . , , , .

, , , .

, orphanRemoval .

0

All Articles