简体   繁体   English

在 Hibernate 中检查是否违反外键约束的正确方法?

[英]Correct way to check for foreign key constraint violation in Hibernate?

I have two tables that already exist inside postgres, lets call the Table A and Table B. One column of Table B has a foreign key constraint in that it has to be the primary key of Table A. Thus there is a many-to-one relationship between B and A, where multiple records in Table B correspond to one record of Table A.我有两个表已经存在于 postgres 中,我们称之为表 A 和表 B。表 B 的一列有一个外键约束,因为它必须是表 A 的主键。因此有一个多对- B和A的一种关系,B表的多条记录对应A表的一条记录。

The Entity for both these tables are defined as follows.这两个表的实体定义如下。

public class TableA implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "user_id")
private Long userId;

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

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

@Column(name = "phone_number")
private String phoneNumber;
}

TableB's entity is defined as follows: TableB的实体定义如下:

public class Shots implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "item_id")
private Long itemId;

@Column(name = "user_id")
private Long userId;
}

Where userId is the foreign key mapping to the primary key user_id in Table A. These constraints have already been defined in the underlying postgres database, so i didn't consider using the @ManyToOne annotation relationship (still trying to wrap my head around it).其中 userId 是外键映射到表 A 中的主键 user_id。这些约束已经在底层 postgres 数据库中定义,所以我没有考虑使用 @ManyToOne 注释关系(仍在尝试绕过它) .

The way i currently handle the case when a foreign key constraint violation occurs is by doing the following:我目前处理发生外键约束冲突的情况的方式是执行以下操作:

try {
        tableBrepository.save(newShot);
    } catch (ConstraintViolationException ex) {
        logger.error("Violating foreign key constraint" + ex.getMessage());
    }

My question is, is there a better way to check for this violation?我的问题是,有没有更好的方法来检查这种违规行为? Is there anything i can do to generally better structure the foreign key constraint in Spring Data JPA?我能做些什么来更好地构建 Spring 数据 JPA 中的外键约束?

Thus there is a many-to-one relationship between B and A, where multiple records in Table B correspond to one record of Table A.因此B和A之间存在多对一的关系,B表中的多条记录对应A表中的一条记录。

This kind of stuff in JPA entities is handled with @ManyToOne annotation. JPA 实体中的这种东西是用@ManyToOne注释处理的。 You usually do not refer to any id field directly but tell JPA what there should be.您通常不会直接引用任何id字段,而是告诉 JPA 应该有什么。 So in your class TableB (or should I call it... Shots?) should be something like:因此,在您的 class TableB 中(或者我应该称它为...镜头?)应该是这样的:

@ManyToOne
private TableA tableA;

// and get rid of this
// @Column(name = "user_id")
// private Long userId;

And optionally - so not necessarily - you could have, in your TableA:并且可选地 - 所以不一定 - 你可以在你的 TableA 中拥有:

@OneToMany
private List<TableB> tableBsOrShouldICallYouShots;

I am not sure what is your actual problem but when setting and referring to id fields directly might cause your difficulties.我不确定您的实际问题是什么,但是直接设置和引用 id 字段可能会给您带来困难。

Now if you -for example- use repository to find some TableB you can then after that just do现在,如果您 - 例如 - 使用存储库来查找一些TableB ,那么您可以在那之后做

tableB.getTableA()

And when saving you would before that do:在保存之前你会做:

tableB.setTableA(somSortOftableA);
// so not tableB.setUserId(someLongIdFOrtableA);

Now the point is that there is no problem with referential integrity because you do not need to know any IDs and you cannot set any wrong ID.现在的重点是参照完整性没有问题,因为您不需要知道任何 ID,也不能设置任何错误的 ID。 Unless you first need to fetch TableA by id before setting it to TableB but in that case you would still not set any IDs.除非您首先需要在将 TableA 设置为 TableB 之前通过 id 获取它,但在那种情况下您仍然不会设置任何 ID。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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