1

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;
}
Dada
  • 6,313
  • 7
  • 24
  • 43
whizkey
  • 11
  • 2

1 Answers1

0

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)
Shankar
  • 2,625
  • 3
  • 25
  • 49
  • 1
    I'm going to give #2 and #3 a shot as #1 isn't an option for us. I'll comment results. – whizkey Jan 05 '22 at 16:09
  • Unfortunately #2 doesn't work because the SimpleJdbcRepository implementation is used for all children as well as the parent and #3 is for JPA. – whizkey Jan 06 '22 at 22:18