gpt4 book ai didi

java.sql.SQLException : Field foreign_key doesn't have a default value

转载 作者:太空宇宙 更新时间:2023-11-04 10:12:09 25 4
gpt4 key购买 nike

我有以下模型结构:

@Entity
@Table(name = "MY_TEMPLATE")
public class MyTemplate {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID", nullable = false, updatable = false)
private Long id;
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "MY_TEMPLATE_ID")
private List<MyObject> myobjects = new ArrayList<>();
...
}

@Entity
@Table(name = "MY_OBJECT")
public class MyObject implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID", nullable = false, updatable = false)
private Long id;
}

MyDailyResource 没有引用 MyTemplate

我还有常用的CrudRepository:

public interface MyTemplateRepository extends CrudRepository<MyTemplate, Long> {
}

当我执行时:

myTemplateRepo.save(myTemplate)//myTemplate 在 myObjects 集合中有一个元素

我看到以下错误:

    insert 
into
MY_TEMPLATE
(LAST_MODIFIED, LAST_MODIFIED_BY, NAME)
values
(?, ?, ?)


insert
into
MY_OBJECT
(BAR, FOO)
values
(?, ?)

java.sql.SQLException: Field 'MY_TEMPLATE_ID' doesn't have a default value
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)

我不知道我做错了什么以及如何解决它。

请问您能给我推荐一些东西吗?

附注

看起来是因为我在数据库中没有该外键的空约束。但我不想消除这个限制

最佳答案

希望您的父表是 MY_TEMPLATE,子表是 MY_OBJECT

更新你的类(class)

@Entity
@Table(name = "MY_TEMPLATE")
public class MyTemplate {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID", nullable = false, updatable = false)
private Long id;
@OneToMany(mappedBy="myTemplate", cascade = CascadeType.ALL, orphanRemoval = true)
private List<MyObject> myObjects = new ArrayList<>();
...
}

@Entity
@Table(name = "MY_OBJECT")
public class MyObject implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID", nullable = false, updatable = false)
private Long id;
@ManyToOne
@JoinColumn(name = "MY_TEMPLATE_ID")
private MyTemplate myTemplate;
}

关于java.sql.SQLException : Field foreign_key doesn't have a default value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52170726/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com