简体   繁体   中英

Hibernate Cascade.All property doesn't add ON DELETE CASCADE on Postgres Foreign Key Constraint

I am using SpringBoot + PostgreSQL + JPA Hibernate, everything seems to working fine however the Cascade.ALL property is not applied on the table user_roles. Am i missing anything important. I have tried ManytoMany relationship and ManytoOne but no luck yet.

The entity files I am using are as follows.

User.java

@Entity
@Table(name = "USERS")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class User {


  @Id
  @SequenceGenerator( name = "lineupSeq", sequenceName = "lineup_seq", allocationSize = 20, initialValue = 50 )
  @GeneratedValue( strategy = GenerationType.SEQUENCE, generator = "lineupSeq" )
  @Column(name="id")
  private Long id;

  @Column(unique=true)
  private String username;

  @Column
  @JsonIgnore
  private String password;

  @Column(name="prodcrud")
 private String prodcrud;

  @Column(name="devcrud")
  private String devcrud;

  @Column(name="testcrud")
  private String testcrud;



@ManyToOne(fetch = FetchType.EAGER, cascade=CascadeType.ALL)
@JoinTable(name = "user_roles", 
    joinColumns = {@JoinColumn(name = "user_id", referencedColumnName="id") },
    inverseJoinColumns = {@JoinColumn(name = "role_id", referencedColumnName="id") })
private Role role;

public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}

Screenshot of postgres constraint added Postgres constraint added

Yes, you simply expect this annotation to do something it doesn't do.

Cascade.ALL tells JPA that every operation (persist, merge, delete, etc.) done, at runtime, using JPA, on a User must also be applied on its role .

Note that it doesn't make sense: since it's a ManyToOne , trying to delete the role of a user when deleting the user will lead to broken foreign key constraints, since the same role is also referenced by other users.

Read the documentation. Don't guess what annotations do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM