Reputation: 849
I am new to stack overflow and working on spring jpa data with hibernate and mysql. I have created One JpaRepository for each entity class. But now I feel that I should use One repository for all entities because In all my repositories has common CRUD operation methods.
save()
update()
delete()
findOne()
findAll()
Besides of above methods, I have other custom methods also in my applications.
my aim is to implement GenericRepo like,
public interface MyGenericRepo extends JpaRepository<GenericEntity,Integer>
{
}
my entities will be like:
class Place extends GenericEntity
{
private Event event;
}
class Event extends GenericEntity
{
}
class Offer extends GenericEntity
{
private Place place;
}
class User extends GenericEntity
{
private Place place;
}
when I call:
MyGenericRepo myRepo;
GenericEntity place=new Place();
myRepo.save(place);
It should save place.
[http://openjpa.apache.org/builds/1.0.2/apache-openjpa-1.0.2/docs/manual/jpa_overview_mapping_inher.html#jpa_overview_mapping_inher_joined][1]
I have referred above link and I found that Jpa Inheritance with Joined and Table-Per-Class strategies are similar to what I am looking for, but these all have certain limitations.So please tell me should I try to implement this generic thing.If I get any demo code then I will be very greatful...
Thanks..
How to make generic jpa repository? Should I do this? Why?
Upvotes: 3
Views: 12754
Reputation: 3652
If you want to create your own Repos (and not spring data which does some work for you) your example isn't bad, i am using a similar strategy in one application.
Here a few thoughts to improve the generic way: I've added the ID-information in my basic domain which is implemented by all domain objects:
public interface UniqueIdentifyable<T extends Number> {
T getId();
void setId(T id);
}
In the next step i've created a generic CRUDRepo:
public interface CRUDRepository<ID extends Number, T extends UniqueIdentifyable<ID>>{
ID insert(T entity);
void delete(T entity);
....
}
And I am using an abstract class for the CRUDRepo:
public abstract class AbstractCRUDRepo<ID extends Number, T extends UniqueIdentifyable<ID>> implements CRUDRepo<ID, T>, {...}
a domain repo api will now look like:
public interface UserRepo extends CRUDRepo<Integer, User > {
User mySpecificQuery(..);
}
and finally you can implement your repo via:
public class UserRepoImpl extends AbstractCRUDRepo<Integer, User > implements UserRepo {
public User mySpecificQuery(..){..}
}
Upvotes: 4