Spring Data JPA and the id field

When you make mistakes you learn more. Since this is true I can tell you that I am learning a lot every day.

Today I learned that your id field type in the entity need to be the same as the generics in the interface that implements the Spring Repository (CrudRepository in my case).

My entity has some code similar to this:

@Entity
public class Table {

    @Id
    @GeneratedValue
    private Long id;
    // more fields
}

And the code for the Repository is something similar to this:

public interface TableRepository extends CrudRepository<Table, Long> {
}

My mistake today was that my id field in the Table class was a int. My Spring application was returning this generic error message:

Could not execute JDBC batch update; SQL [insert into Table (name, id) values (?, ?)]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update

Bonus: I also learned that it will throw the same error if you try to insert twice the same name value.

Advertisements

Published by

m5c

Java developper that loves photography and good coffee

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s