当我尝试保存
没有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 {}
最佳答案
MY_CONFIG_ID
列不是 Hibernate
映射的一部分。
插入查询插入到字段id
和value
中。然后,必须有名为 MY_CONFIG_ID
的第三列,该列未在 entity
中提及,因此将被插入为 null
。如果此列有一个 not null
约束,它将失败。
如果您希望将 id
列命名为 MY_CONFIG_ID
,那么您需要 ovveride 默认列名称(id
,与变量)通过使用 @Column(name="MY_CONFIG_ID")
注释它,如果您想使用默认名称 id
您需要删除该列(或至少非空约束。)
关于java - Spring JPA插入id等于null的实体(应该自动生成),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41569053/