王奕然
王奕然

Reputation: 4049

spring data jpa save manually assign identifier

i use spring save

  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> {

    }

the table is like f_id varchar(256) NOT NULL,

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

but throws exception

Caused by: java.sql.SQLException: Field 'f_id' doesn't have a default value at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:946) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2870) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1573) at com.mysql.jdbc.ServerPreparedStatement.serverExecute(ServerPreparedStatement.java:1169) at com.mysql.jdbc.ServerPreparedStatement.executeInternal(ServerPreparedStatement.java:693) at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1404) at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1318) at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1303) at com.alibaba.druid.pool.DruidPooledPreparedStatement.executeUpdate(DruidPooledPreparedStatement.java:253) at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:208) ... 51 more

i check the document, Id-Property inspection (default) By default Spring Data JPA inspects the Id-Property of the given Entity. If the Id-Property is null, then the entity will be assumed as new, otherwise as not new.

the sql is like Hibernate: insert into us_highway (blockTime, blockType, endNum, predictTime, publishTime, roadName, situation, startNum, tips) values (?, ?, ?, ?, ?, ?, ?, ?, ?) not id is insert!

because i want to assign id manually,the id-property is not null if new ,how to configure to save ?

Upvotes: 1

Views: 5140

Answers (1)

dReAmEr
dReAmEr

Reputation: 7196

If you are assigning Id manually.Remove below annotation on id.

@GeneratedValue(strategy = GenerationType.IDENTITY)

Upvotes: 6

Related Questions