Spring Data JDBC Lookup Tables Cascading Deletes

Viewed 270

I have a structure similar to below. I need to only retrieve the lookup data but not have it deleted/saved/updated when a parent/child is deleted/saved/updated. The data in the lookup table is static. I'm using Sprint Data JDBC with Java 11 with Postgres for the database. I understand this is a contrived example but I am not allowed to post the actual code.

@Data
@Table("parent")
public class ParentDTO {

    @Id
    private long parentId;
    private Date createdAt;
    @MappedCollection(idColumn="parent_id", keyColumn="parent_id")
    private Set<ChildDTO> children;
    String name;
}

@Data
@Table("child")
public class ChildDTO {

    @Id
    private long childId;
    private Date createdAt;
    private long parentId;
    String name;

    @MappedCollection(idColumn="lookup_id", keyColumn="lookup_id")
    private LookupDTO lookupDTO;
}

@Data
@Table("lookup")
public class LookupDTO {

    @Id
    private long lookupId;
    String name;
    private Date createdAt;
}
1 Answers

Cascade is not an optional feature in JPA/Spring-Data that can be entirely removed. The entity relations will have a default cascade option, since it is a reflection of the underlying database schema.

In your example, if the ParentDTO is deleted, how can the ChildDTO that has a foreign key (ChildDTO.parentId) exist in the database? The Spring-Data JPA just reflects this design.

If you want to make sure nobody deletes the ParentDTO or other entities, then you can do several things:

Here are some ideas:

  1. Change the Database access to these tables to be read-only for your JDBC user id. If they are static, this is how it should be.
  2. Make the Repository read-only. Here is a good discussion on that - Creating a read-only repository with SpringData
  3. Force your entity to be read-only. The top answer here is the best - How to make an Entity read-only? (Implement an EntityListener, or just remove all setter methods from your entities)
Related