Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA / Spring / Delete Entity, type Mismatch (int/long for id)

I have an Entity which uses

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;

and i have a JPA Repository for this Entity. Now i want to delete one of those, but the standard method for that is delete(int i), which can't work because my ID's are not Integers, but Longs. So apart from using int for my IDs, what to do here? Can i specify a custom delete method which uses long, like it works with findbyXX(XX) ?

EDIT: First of all: Yes i am using Data JPA!

I want to do this:

   jparepository.delete(id);

In case id is an Integer:

org.hibernate.TypeMismatchException: Provided id of the wrong type for class com.Entity. Expected: class java.lang.Long, got class java.lang.Integer

In case id is a long:

no method found for delete(long)

So i can either change my ID to int, which i don't want to do, or find a way to get the Repository to work with long. And the question is how

like image 871
Heady Avatar asked Jan 08 '16 01:01

Heady


3 Answers

Ok turns out it was just a stupid mistake. So my JPARepository looked like this:

public interface EntityRepository extends JpaRepository<Entity, Integer> {

But Integer represents the type of the Entities ID-Field, which is Long in my case. So i needed to change to ..JpaRepository<Entity, Long>

like image 141
Heady Avatar answered Oct 12 '22 21:10

Heady


If you are using Spring Data JPA, the default delete method is:

void delete(T entity); 

Look here: Spring Data JPA Docs

Also, you it's better to use Long than primitive long, because then you can use more methods when validating:

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
like image 22
m.aibin Avatar answered Oct 12 '22 21:10

m.aibin


Assuming you are talking about spring data JPA, yes you can specify a custom method if you want to delete by something user-defined, but that isn't necessary for a delete by ID. See the spring docs:

http://docs.spring.io/spring-data/data-commons/docs/current/api/org/springframework/data/repository/CrudRepository.html#delete-ID-

You can delete by a generic ID type that corresponds to the type of your entities' ID (in your case Long). This should work.

like image 32
leeor Avatar answered Oct 12 '22 19:10

leeor