P
P
piatachki2017-10-26 16:29:35
SQL
piatachki, 2017-10-26 16:29:35

Why does CrudRepository#save() throw a duplicate entry?

In the process of studying the topic, I ran into a problem. There is a CrudRepository and this VersionedEntity:

@Entity
@Table(name = "version_table")
public class VersionedEntity {

    @Id
    @Column(name = "id")
    private int id;

    @Column(name = "first_field")
    private String firstField;

    @Column(name = "second_field")
    private String secondField;

    public VersionedEntity() {
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getFirstField() {
        return firstField;
    }

    public void setFirstField(String firstField) {
        this.firstField = firstField;
    }

    public String getSecondField() {
        return secondField;
    }

    public void setSecondField(String secondField) {
        this.secondField = secondField;
    }

    @Override
    public boolean equals(Object obj) {
        return obj instanceof EntityRepository && ((VersionedEntity) obj).id == this.id;
    }
}

Why code:
public static void main(String[] args) {

        ApplicationContext ctx = SpringApplication.run(Application.class, args);
        EntityRepository repository = (EntityRepository) ctx.getBean("entityRepository");

        VersionedEntity entity = repository.findOne(0);
        entity.setFirstField("ffsv");

        repository.save(entity);

    }

causes "Duplicate entry '0' for key 'PRIMARY'" error? It seems that the method should check for the presence of an object with the given id in the table and, if so, do an update. At least always such tricks passed. Here he broke his head. Or I don't understand something.
Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Kosarev, 2017-10-27
@jaxtr

The id must have the @GeneratedValue annotation:

@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question