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
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>
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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With