我看到了一些问题,但没有找到任何对我有帮助的答案。
@Filters({
@Filter(name = "shoesFilter", condition = ":minShoeSize <= shoeSize and :maxAge >= shoeSize"),
@Filter(name = "shoesFilter", condition = ":minNumber <= number")
})
@Entity
@Table(name = "Shoes",catalog = "shoues")
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Shoes {
@Id
@Column(name = "id")
private Integer id;
@Column(name = "shoe")
private Integer shoeSize;
}
我在hbm.xml中定义了
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<filter-def name="shoesFilter">
<filter-param name="maxShoeSize" type="integer"/>
<filter-param name="minShoeSize" type="integer"/>
<filter-param name="minNumber" type="integer"/>
</filter-def>
</hibernate-mapping>
之后,我将我的代码称为
public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession();
System.out.println("enable filter");
Filter filter = session.enableFilter("shoesFilter");
filter.setParameter("maxShoeSize", 40);
filter.setParameter("minShoeSize", 22);
filter.setParameter("minNumber", 27);
session.beginTransaction();
List<Shoes> result = session.createQuery("from Shoes").list();
for (Shoes s : result) {
System.out.println("sad" + s.getShoeSize() + "fds" + s.getId());
}
System.out.println("--Apply where clause--");
System.out.println("--Disable Filter--");
session.disableFilter("shoesFilter");
session.close();
}
但是当我运行代码时,我会得到以下错误。
Exception in thread "main" org.hibernate.HibernateException: No such filter configured [shoesFilter]
at org.hibernate.internal.SessionFactoryImpl.getFilterDefinition(SessionFactoryImpl.java:982)
at org.hibernate.engine.spi.LoadQueryInfluencers.enableFilter(LoadQueryInfluencers.java:134)
at org.hibernate.internal.SessionImpl.enableFilter(SessionImpl.java:2327)
at com.example.hibernateperformance.HibernatePerformanceApplication.main(HibernatePerformanceApplication.java:25)
我看到了很多关于这个话题的问题和答案,但这些答案对我没有帮助。你看到的有遗漏的项目吗?
我意识到哪里出了问题。正如你所看到的,我写了
HibernateUtil.getSessionFactory().openSession();
像里面的这个
@Component
public class HibernateUtil {
private static SessionFactory sessionFactory ;
static {
Configuration configuration = new Configuration().configure("shoes.hbm.xml");
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
sessionFactory = configuration.buildSessionFactory(builder.build());
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
此处->Configuration((.configure("shoes.hbm.xml"(;我之前没有在configure中给出文件路径,所以它看不到过滤器是在哪里定义的。