首页 > 解决方案 > 如何从表 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。

非常感谢!

标签: javasqlspringspring-boot

解决方案


您必须像在行中一样创建构造函数接收两个参数:

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 方法。希望它有效!


推荐阅读