Spring Generic Dao class name

后端 未结 3 1372
时光说笑
时光说笑 2020-12-04 00:30

I have configured a custom generic service DAO for my spring / hibernate project - the idea being that I can reuse it easily from my controllers.

It essentially look

3条回答
  •  死守一世寂寞
    2020-12-04 01:11

    I did something similar, you need the generic class to be a constructor argument as well, mine uses hibernate entities, but you could pass in the string of table name.

    public class DomainRepository {
    
        @Resource(name = "sessionFactory")
        protected SessionFactory sessionFactory;
    
     public DomainRepository(Class genericType) {
            this.genericType = genericType;
        }
    
     @Transactional(readOnly = true)
        public T get(final long id) {
            return (T) sessionFactory.getCurrentSession().get(genericType, id);
        }
    

    You can then subclass (if you need to) to customize or simply set up you bean in the spring config like below t :

    
            
    
    

    So in your code you could then reference tagRepository like so (no other cod eis needed than that posted above, and below) :

    @Resource(name = "tagRepository")
    private DomainRepository tagRepository;
    

    Also, I would call it a repository not a service, a service deals with different types and their interactions (not just one). And for specifically your example using SQL strings :

    public final String tableName;
    public DomainRepository(String tableName) {
          this.tableName = tableName;
    }
    public List getAll(Integer status) {
        Session session = sessionFactory.getCurrentSession();
        Query query = session.createQuery("FROM " + tableName + " WHERE status = " + status);
        return query.list();
    }
    

    and have your beans defined like so

    
      
    
    

    And then you can alsow create subclasses youself where necessary :

    public class PersonRepository extends DomainRepository {
        public PersonRepository(){
            super("person"); //assumes table name is person
        }
    

提交回复
热议问题