java – Spring MVC:通用DAO和服务类

我正在Spring MVC中编写Web.我使用Generic DAO编写了所有DAO.现在我想重写我的服务类.我怎么写“通用服务”?

有我的DAO:

/* ################################# DAO ################################ */
package net.example.com.dao;

import java.util.List;

public interface GenericDaocope;

@Scope("prototype")
public abstract class GenericHibernateDaoImplcreatequery("FROM " + clazz.getName()).list();              
        }

        public void update(T entity) {
                getCurrentSession().update(entity);            
        }

        public void save(T entity) {
                getCurrentSession().save(entity);              
        }

        public void delete(T entity) {
                getCurrentSession().delete(entity);            
        }

        protected final Session getCurrentSession(){
                return sessionFactory.getCurrentSession();
        }
}

/* ------------------------------------------------------ */

package net.example.com.dao;

import net.example.com.entity.Country;

public interface CountryDao extends GenericDaocreatequery("FROM Country WHERE name = :name")
                                .setString("name",name).uniqueResult();
        }

        @Override
        public Country findByCode(String code) {
                return (Country) getCurrentSession()
                                .createquery("FROM Country WHERE code = :code")
                                .setString("code",code).uniqueResult();
        }

}

/* ################################# DAO ################################ */

和服务:

/* ################################# SERVICE ################################ */

package net.example.com.service;

import java.util.List;

public interface GenericManager

编译器(和Eclipse)没有看到findByName和findByCode方法.我理解为什么.但是我怎么能重写呢?

最佳答案
我仍然不知道为什么人们实际使用古老的DAO /服务模型与Spring Data;完全不必要,容易出错等等.

Spring Data JPA有一些非常有用的接口:JpaRepositoryJpaSpecificationExecutor – 这些封装了你想要的一切,你只需要你的标准实体就可以了 – 其他一切都将由spring处理,你只需输入你的标准并得到什么你想要,而不是重新发明轮子.
可能是你没有真正阅读文档?它非常有用:

官方介绍:http://spring.io/blog/2011/04/26/advanced-spring-data-jpa-specifications-and-querydsl/

doc:http://docs.spring.io/spring-data/jpa/docs/1.7.0.RELEASE/reference/html/

小编:http://www.cubrid.org/wiki_ngrinder/entry/how-to-create-dynamic-queries-in-springdata

来自天才的例子:https://github.com/spring-projects/spring-data-jpa-examples/tree/master/spring-data-jpa-example

示例类:

public CustomerSpecifications {

  public static Specificationssthan(root.get(Customer_.createdAt),new LocalDate.minusYears(2));
      }
    };
  }
}

public interface CustomerRepository extends JpaRepository

现在您可以简单地自动装配您的存储库:

@Autowired
CustomerRepository customerRepo;

并检索这样的数据:

List

这很容易.

相关文章

这篇文章主要介绍了spring的事务传播属性REQUIRED_NESTED的原...
今天小编给大家分享的是一文解析spring中事务的传播机制,相...
这篇文章主要介绍了SpringCloudAlibaba和SpringCloud有什么区...
本篇文章和大家了解一下SpringCloud整合XXL-Job的几个步骤。...
本篇文章和大家了解一下Spring延迟初始化会遇到什么问题。有...
这篇文章主要介绍了怎么使用Spring提供的不同缓存注解实现缓...