java - java JPA中的多个外键
问题描述
我想在数据库中保留 Class2 的一个实例。但是当我向'/two'发送GET请求时,它会报告异常org.postgresql.util.PSQLException: ERROR: null value in column "id1" of relation "class2" violates not-null constraint Detail: Failing row contains (2, null, null, 1).
我该怎么做才能成功持久化 Class2 的新实例。是否可以使PK成为Class2的主键(PK是Class1的主键和Class2的外键,我想使它成为Class2的主键)
Class1.java
@Table
@Entity
@Data
@IdClass(PK.class)
@AllArgsConstructor
@NoArgsConstructor
public class Class1{
@Id
private int id1;
@Id
private int id2;
private int one;
}
Class2.java
@Table
@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Class2{
@Id
private int id;
@OneToOne
@JoinColumns({
@JoinColumn(name = "id1", referencedColumnName = "id1", insertable = false, updatable = false),
@JoinColumn(name = "id2", referencedColumnName = "id2", insertable = false, updatable = false)
})
private Class1 class1;
private int two;
}
控制器
@RestController
public class ForeignController {
@Autowired
Class1Repository repository1;
@Autowired
Class2Repository repository2;
@GetMapping("/one")
public void createone(int id1, int id2, int one){
repository1.saveAndFlush(new Class1(id1, id2, one));
}
@GetMapping("/two")
public void createtwo(int id1, int id2, int two, int id){
Class1 class1 = repository1.getOne(new PK(id1, id2));
repository2.saveAndFlush(new Class2(id, class1, two));
}
}
解决方案
代替@IdClass,使用@EmbeddedId
@Table
@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Class1{
@EmbeddedId
private PK pk;
private int one;
}
public class Class2{
@EmbeddedId
private PK pk;
@MapsId
@OneToOne
private Class1 class1;
private int two;
}
推荐阅读
- sqlalchemy - 使用 SQLAlchemy,我如何仅使用 json 更新数据库?
- javascript - 在 Nuxt 中从 .env 设置开发或生产 api URL
- sql - 如果满足多个条件,则从同一个表中的行中复制数据
- python - 如何根据具有相同字段值的对象总数在模型中添加自动增量字段?
- c - 从函数返回后如何将信息保存在结构中?
- dev-c++ - 从 Dev C++ 项目中删除文件
- javascript - 将已解决的承诺返回到另一个文件
- batch-file - 用用户输入的文本替换文件/目录名称
- c# - 在 C# 中创建一个类数组
- java - 使用 jpackage 构建我的 JavaFX 应用程序后的数据库错误连接