java - 如何从表 a 中获取插入的 id 并使用该 id 插入表 b
问题描述
我想在表a中保存一条记录并获取插入的id;并将此 id 保存到表 b 中的另一条记录中。
服务中:
public Long save(Entity entity, String a) {
entity = entityRepository.saveAndFlush(entity);
Long insertedEntityId = entity.getId();
EntityB entityb = new EntityB(
insertedEntityId,
a);
entityb = entityBRepository.saveAndFlush(entityb);
return entityb.getId();
}
在实体 B 中:
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
public Long getId() {
return id;
}
但是,我得到了错误:
com.microsoft.sqlserver.jdbc.SQLServerException: Cannot insert the value NULL into column 'id', table '...'; column does not allow nulls. INSERT fails.
如何解决这个问题?
我正在使用 SQL Server 2012、Spring Boot 2.3、Java 11。
非常感谢!
解决方案
您必须像在行中一样创建构造函数接收两个参数:
EntityB entityb = new EntityB(insertedEntityId, a);
在该构造函数中,假设如下:
public EntityB(Long id, String param) {
this.id = id;
this.param = param;
}
线条
public Long getId() {
return id;
}
不正确,它只是用于检索 id 的 getter 方法。希望它有效!
推荐阅读
- python - Numpy第n个奇数根,包括负值
- tensorflow - 如何从经过 tf.estimator 训练的 CNN 获得预测
- android - 不同机器安装的 Android 应用程序(通过 Android Studio)会得到不同的签名吗?
- json - 在 Scratch 3.0 中编辑 JSON 文件
- vba - 突出显示单元格而不是特定单元格的宏
- c++ - C++:读取 Lambda 捕获的指针时发生访问冲突
- java - Hibernate:从不同类路径的 jar 中自动加载标记为 @Entity 的类
- mongodb - 具有多个条件的 pymongo db 查询 - $ 和 $exists
- php - elasticsearch php嵌套聚合
- java - 如何检查包含 ArrayList 的 ArrayList 中是否存在值