首页 > 解决方案 > Spring Boot:尽管我在@JoinColumn 注释中添加了“NO_CONSTRAINT”属性,但为什么我无法插入条目?

问题描述

我试图在“txt_auth_a”表中插入一个条目,该表以 auto_inc_id 作为主键,“account_id”作为外键,因此 account_id 和 auto_inc_id 之间存在一对一的关系。auto_inc_id 也是“txt_account”表的主键。

文本帐户实体:

@Entity
@Table(name="txt_account")
public class TextAccount 
{
    
    //
    
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    //@Column(name="auto_inc_id" , nullable=false, updatable=false, insertable=false)
    @OneToOne(mappedBy="TextAuthA.class")
    @JoinColumn(name="auto_inc_id",nullable=false , foreignKey = @ForeignKey(value = ConstraintMode.NO_CONSTRAINT))
    private int auto_inc_id;

txt_auth_a 实体:

@Entity
@Table(name="txt_auth_a")
public class TextAuthA 
{
    //
    
    //@JoinColumn(name="auto_inc_id",nullable=false , foreignKey = @ForeignKey(value = ConstraintMode.NO_CONSTRAINT))
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name="auto_inc_id" , nullable=false)
    private int auto_inc_id;
    
    //@Column(name="account_id" , nullable=false)
    @OneToOne(targetEntity = TextAccount.class, cascade=CascadeType.ALL)
    @JoinColumn(referencedColumnName = "auto_inc_id", foreignKey = @ForeignKey(value = ConstraintMode.NO_CONSTRAINT), updatable=false, insertable=false)
    private int account_id;

我在 DAO 中为 txt_auth_a 运行的查询是:

@Modifying
    @Transactional
    @Query(value="INSERT INTO txt_auth_a (account_id, username, email, password) VALUES(:accid , :username , :email , :password )",
            nativeQuery=true)
    public void signup(int accid, String username, String email, String password);

尽管我说@ForeignKey(value = ConstraintMode.NO_CONSTRAINT),但我收到了外键约束的错误

java.sql.SQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`megamadz`.`txt_auth_a`, CONSTRAINT `txt_auth_a_ibfk_1` FOREIGN KEY (`account_id`) REFERENCES `txt_account` (`auto_inc_id`) ON DELETE CASCADE ON UPDATE CASCADE)

标签: javaspring-bootforeign-keys

解决方案


推荐阅读