我正在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方法.我理解为什么.但是我怎么能重写呢?
Spring Data JPA有一些非常有用的接口:JpaRepository和JpaSpecificationExecutor – 这些封装了你想要的一切,你只需要你的标准实体就可以了 – 其他一切都将由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
这很容易.
原文地址:https://www.jb51.cc/spring/432344.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。