Spring等于null的Spring JPA插入实体(应该是自动生成的)

时间:2017-01-10 12:37:36

标签: java spring hibernate jpa spring-data-jpa

当我尝试save没有id的实体时,Spring的JpaRepository会引发异常:

MyConfig config = new MyConfig();
config.setValue("value");
myConfigRepository.save(config);

如何让Hibernate不在插入查询中包含id字段?

org.h2.jdbc.JdbcSQLException: NULL not allowed for column "MY_CONFIG_ID"; SQL statement:
insert into my_config (value, id) values (?, ?) [23502-190]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
    at org.h2.message.DbException.get(DbException.java:179)
    at org.h2.message.DbException.get(DbException.java:155)
    at org.h2.table.Column.validateConvertUpdateSequence(Column.java:305)
    at org.h2.table.Table.validateConvertUpdateSequence(Table.java:749)
    at org.h2.command.dml.Insert.insertRows(Insert.java:151)
    at org.h2.command.dml.Insert.update(Insert.java:114)
    at org.h2.command.CommandContainer.update(CommandContainer.java:78)
    at org.h2.command.Command.executeUpdate(Command.java:253)
    at org.h2.server.TcpServerThread.process(TcpServerThread.java:345)
    at org.h2.server.TcpServerThread.run(TcpServerThread.java:159)
    at java.lang.Thread.run(Thread.java:745)

我的实体:

@Entity
public class MyConfig {

    @Id
    @SequenceGenerator(sequenceName = "MY_CONFIG_SEQ", name = "MyConfSeq", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "MyConfSeq")
    private Long id;

    @Column
    private String value;

    //getters & setters

和存储库:

public interface MyConfigRepository extends JpaRepository<MyConfig, Long>, JpaSpecificationExecutor {}

1 个答案:

答案 0 :(得分:1)

MY_CONFIG_ID不属于您的Hibernate映射。

插入插入idvalue字段的查询。然后,必须有一个名为MY_CONFIG_ID的第三列,entity中未提及,因此将插入null。如果此列具有not null约束,则它将失败。

如果您希望将id - 列命名为MY_CONFIG_ID,则需要使用{{1}注释默认列名称id,与变量相同“如果你想使用默认名称@Column(name="MY_CONFIG_ID"),你需要删除列(或至少是非空约束。)