实体定义,Shops.java:
package youway.model;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.persistence.Table;import org.hibernate.annotations.Filter;import org.hibernate.annotations.FilterDef;import org.hibernate.annotations.Filters;import org.hibernate.annotations.ParamDef;@Entity@Table(name = "shops")@FilterDef(name = "employeeFilter", parameters = { @ParamDef(name = "emplNumber", type = "integer") })@Filters({ @Filter(name = "employeeFilter", condition = ":emplNumber <= employees_number") })public class Shop { @Id @GeneratedValue private Integer id; /** 店铺名称 */ private String name; /** 员工编号 */ @Column(name = "employees_number") private Integer emplNumber; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getEmplNumber() { return emplNumber; } public void setEmplNumber(Integer emplNumber) { this.emplNumber = emplNumber; }}
其中,
@FilterDef(name = "employeeFilter", parameters = { @ParamDef(name = "emplNumber", type = "integer") })@Filters({ @Filter(name = "employeeFilter", condition = ":emplNumber <= employees_number") })
是要过滤 employees_number (数据库字段名)大于等于指定参数 emplNumber (自定义参数名)的记录
在Hibernate中调用代码片段:
public ListfindAll(){ Session session = HibernateUtil.getSessionFactory().openSession(); System.out.println("--过滤生效--"); Filter filter = session.enableFilter("employeeFilter"); filter.setParameter("emplNumber", new Integer(24)); session.beginTransaction(); List results = session.createQuery("from Shop").list(); for(Shop: results){ System.out.println("店铺名称:"+s.getName()+", 员工编号:"+s.getEmplNumber()); } session.disableFilter("employeeFilter"); session.close(); return results; }
利用 spring data jpa定义ShopRepository.java:
package youway.repository;import org.springframework.data.jpa.repository.JpaRepository;import youway.model.Shop;public interface ShopRepository extends JpaRepository{}
利用 spring data jpa调用:
package youway.service;import java.util.List;import javax.annotation.Resource;import javax.persistence.EntityManager;import javax.persistence.PersistenceContext;import org.hibernate.Filter;import org.hibernate.Session;import org.springframework.stereotype.Service;@Servicepublic class ShopService{ @PersistenceContext private EntityManager entityManager; @Resource private ShopRepository shopRepository; @Transactional public ListfindAll() { Filter filter = (Filter)entityManager.unwrap(Session.class).enableFilter("employeeFilter"); filter.setParameter("emplNumber", new Integer(1000)); List lists = shopRepository.findAll(); entityManager.unwrap(Session.class).disableFilter("employeeFilter"); return lists; }}