问题
Assume I have a Entity called Product
. I design a Repo as
@Repository
interface ProductRepository implements JPARepository<Product, Integer>{}
This would inherit all the default methods such as save, findAll
etc;
Now I want to have one custom method, which is also a common method for other entities. I added another interface and implementation
interface CustomRepository<T,ID>{ public void customMethod() }
class CustomRepositoryImpl implements CustomRepository<T,ID>{ public void customMethod(){} }
And I rewrite the ProductRepository as
@Repository
interface ProductRepository implements
JPARepository<Product, Integer>,
CustomRepository<Product, Integer>
{}
Now, this does not give me any compilation error. But during runtime, I get this error:
No property 'customMethod' is found for Product
What am I missing?
回答1:
You seem to be trying to add custom behaviour to a single repository, namely ProductRepository
. However, the code is structured as if custom behaviour needs to be added to all repositories (CustomRepository
is not specific to Product
s). Hence, the error.
Step 1: Declare a custom repository
interface CustomRepository<T, ID extends Serializable> {
void customMethod();
}
Step 2: Add custom behaviour to the required repository
interface ProductRepository extends CrudRepository<Product, Integer>
, CustomRepository<Product, Integer> {}
Step 3: Add a
Product
specific implementation
class ProductRepositoryImpl implements CustomRepository<Product, Integer> { ... }
Note: The class must be named ProductRepositoryImpl
for Spring Data JPA plumbing to pick it up automatically.
A working example is available on Github.
If you would rather add custom behaviour to all repositories, refer to the relevant section in the official documentation.
回答2:
Ok. This is for people who are trying to get this work in a SpringBoot application
follow whatever posted by @manish. Working code here Working Code
You just have to make one small change. Define Model class as
@MappedSuperclass
@IdClass(ModelID.class)
public abstract class Model implements Serializable
define the ID class as
public class ModelID implements Serializable{
@Column(name = "id")
@Generated(GenerationTime.INSERT)
@GeneratedValue(strategy = GenerationType.AUTO)
@Id
private Long id;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
This got me working!
来源:https://stackoverflow.com/questions/42337222/add-custom-method-to-jparepository-with-generics