Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Common spring jpa repository with multiple entity finders

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);
}
like image 848
Sannu Avatar asked Oct 18 '22 16:10

Sannu


1 Answers

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

like image 73
Sergio Avatar answered Oct 21 '22 03:10

Sergio