Spring data - Deletion is suppressed with relation to view

Viewed 179

So I have two entities:

@Getter
@Setter
@Entity
@Table(name = "MY_TABLE")
public class MyTable {
    @Id
    @Column(nullable = false, length = 18)
    @SequenceGenerator(name = "MY_TABLE_seq", sequenceName = "MY_TABLE_seq", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "MY_TABLE_seq")
    private long id;

    @OneToOne(mappedBy = "myTable")
    private MyTableView myTableView;
}

And an Immutable entity (the reason for this is that it is a database view):

@Entity
@Getter
@Immutable
@Table(name = "MY_TABLE_VIEW")
public class MyTableView {
    @Id
    @Column(name = "ID", nullable = false, length = 18)
    private Long id;

    @OneToOne
    @MapsId
    @JoinColumn(name = "id")
    private MyTable myTable;
}

Updating and creating the MyTable works without a problem. The problem start when I try to remove the MyTable. I am using the repository for that:

public interface MyTableRepository extends CrudRepository<MyTable,Long> {
}

In the service I am using:

public void deleteMyTable(Long id){
/*fetch the my table enity*/
   myTableRepository.delete(myTable);
}

Nothing happens. No exception nothing at all. What I have tried is changing the @OneToOne mapping. With different cascade:

@OneToOne(mappedBy = "myTable",cascade = CascadeType.ALL)
@OneToOne(mappedBy = "myTable",cascade = CascadeType.DETACH)
@OneToOne(mappedBy = "myTable",cascade = CascadeType.MERGE)
@OneToOne(mappedBy = "myTable",cascade = CascadeType.REFRESH)
@OneToOne(mappedBy = "myTable",cascade = CascadeType.REMOVE)
@OneToOne(mappedBy = "myTable",cascade = CascadeType.PERSIST)
  • ALL,MERGE and REMOVE throws and exception as I can not delete from a view
  • DETACH,REFRESH and PERSIST does nothing but the MyTable entity is not removed

Does anyone have an idea how to resolve this problem?

2 Answers

As indicated in the question comments, I suggested you to try creating some kind of @PreRemove hook in order to avoid the problem.

Because it makes perfect sense according to how the relationship between your entities is defined.

But if you think about that, you are dealing with a view, with a read-only entity: in my opinion, it makes more sense to invert the relationship and make MyTable the owner. In addition probably it will solve the issue.

Please, consider define you relationship with MyTableView in MyTable like this:

@OneToOne
@JoinColumn(name = "id", referencedColumnName = "id")
private MyTableView myTableView;

In MyTableView, simplify your relationship with MyTable in the following way:

@OneToOne(mappedBy = "myTableView")
private MyTable myTable;
Related