spring data jpa保存手动分配标识符

Ami*_*bha 1 spring spring-data spring-data-jpa

我用弹簧保存

  HighWay highWay = new HighWay();
     highWay.setId("000");
    HighWayRepository hRepository = (HighWayRepository) context
                    .getBean("highWayRepository");
            hRepository.save(highWay);
            hRepository.flush();


    public interface HighWayRepository extends JpaRepository<HighWay, String> {

    }
Run Code Online (Sandbox Code Playgroud)

该表就像 f_idvarchar(256) NOT NULL,

public class HighWay {
    @Id
    @Column(name="f_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private String id;}
Run Code Online (Sandbox Code Playgroud)

但抛出异常

引起原因:java.sql.SQLException:字段“f_id”在 com.mysql.jdbc.SQLError.createSQLException(SQLError.java:946) 处没有默认值 com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO. java:2870)在com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1573)在com.mysql.jdbc.ServerPreparedStatement.serverExecute(ServerPreparedStatement.java:1169)在com.mysql.jdbc.ServerPreparedStatement.executeInternal(ServerPreparedStatement .java:693)在com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1404)在com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1318)在com.mysql.jdbc.PreparedStatement.executeUpdate( PreparedStatement.java:1303)在com.alibaba.druid.pool.DruidPooledPreparedStatement.executeUpdate(DruidPooledPreparedStatement.java:253)在org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:208)... 51更多的

我检查文档,Id-Property 检查(默认) 默认情况下,Spring Data JPA 检查给定实体的 Id-Property。如果 Id-Property 为空,则该实体将被假定为新的,否则被假定为非新的。

sql就像Hibernate:insert into us_highway (blockTime, blockType, endNum, predictTime, publishTime, roadName, situation, startNum, tips) values (?, ?, ?, ?, ?, ?, ?, ?, ?) 不是id而是插入!

因为我想手动分配id,如果是新的,id属性不为空,如何配置保存?

RE3*_*350 6

如果您手动分配 ID。请删除 id 上的以下注释。

@GeneratedValue(strategy = GenerationType.IDENTITY)
Run Code Online (Sandbox Code Playgroud)