简体   繁体   中英

spring-data-jdbc update with repository save methods updates ID

Calling CrudRepository save() method for an entity that is NOT new creates following sql: UPDATE card SET id = ?, customer_id = ? ... WHERE id = ?

This raises exception Cannot update identity column 'id'

ID is generated by the database

used version: 1.0.6.RELEASE & 1.0.9.RELEASE

DB: mssql

Why is update statement trying to update the ID column as it is the primary key?

Entity:

import org.springframework.data.annotation.Id;
import org.springframework.data.relational.core.mapping.Column;
import org.springframework.data.relational.core.mapping.Table;

@Table("card")
public class Card {

    @Id
    private Long id;

    @Column("customer_id")
    private String customerId;
...

Repository:

public interface CardRepository extends CrudRepository<Card, String> {
}

This sounds like https://jira.spring.io/browse/DATAJDBC-262 which was fixed and released in version 1.1.M1 the current version of that development branch is 1.1.RC1 .

Switching to that version should solve the problem.

Note: I've seen the exception you mention only with MS-SqlServer which isn't yet fully supported yet.

It seems that you haven't set id generation Strategy for the ID. Add this and try if it is working.

@GeneratedValue(strategy = GenerationType.AUTO) 

If an entity has a primary key field that is not marked with @GeneratedValue, the automatic primary key value is not generated and the application is responsible to set a primary key by initializing the primary key field. That must be done before any attempt to persist the entity object. Also, I think you need to implement Hashcode and Equals for the Card entity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM