My application has over 250 tables with each having ID and name columns. I am trying to migrate our application from hibernate 3 to Spring-JPA 4.3 with hibernate 5+.
In my current hibernate layer I have (Option 1):
public class DAO
{
private Session session;
public DAO(Session session)
{
this.session=session;
}
public EntityA findById(String id)
{
//implementation
return entityA;
}
public EntityB findByName(String name)
{
//implementation
return entityB;
}
public EntityC findByIdAndName(String id, String name)
{
//implementation
return entityC;
}
}
Back in the days i could have done the following with more generic methods but I didn't want to reinitialize this class if i have 10 different entities to fetch by ID.
public class DAO<T>
{
public T findById(String id)
{
//implementation
return T;
}
public T findByName(String name)
{
//implementation
return T;
}
public T findByIdAndName(String id, String name)
{
//implementation
return T;
}
}
Now how can i achieve this in Spring-JPA. So If i need to get 10 different entities by ID, i don't want to initialize 10 repositories, i want to have one repository that i can use to fetch any entity i want byId or byName or byIDAndName. I could do it easily with JdbcTemplate but that means it may not be tracked by JPA/hibernate caching mechanism.
So how can do the following in one JPA repository:
{
@Query("from EntityA where id=?1")
EntityA findEntityAById(String id);
@Query("from EntityB where name=?1")
EntityB findEntityBById(String name);
@Query("from EntityC where id=?1 and name=?2")
EntityC findEntityCById(String id,String name);
}
You should be able to create a super class(es) that has the common attributes, mark it as a @MappedSuperClass and create a repository for that super class as @NoRepositoryBean. You'll just have to do some casting for your results. See this answer
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