hibernate 过滤器

做了一个简单的过滤器

 

我们要用到的持久化类在博客的类继承映射中的是一样的,在此不在列出

 

在这列出配置文件中的相关代码

Users.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
	"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
	<class name="cn.lxl.pojo.Users" table="t_users">
		
		<id name="id">
			<generator class="increment"/>
		</id>
		<property name="username" type="java.lang.String">
			<column name="username"/>
		</property>
		<property name="password" type="java.lang.String">
			<column name="password"/>
		</property>
		<joined-subclass name="cn.lxl.pojo.Admin" table="users_admin">
			<key column="id" foreign-key="id" ></key>
			<property name="manSuc" type="java.lang.String">
				<column name="man_suc"/>
			</property>
		</joined-subclass>
		<joined-subclass name="cn.lxl.pojo.Guest" table="users_guest">
			<key column="id" foreign-key="id"></key>
			<property name="loginTime" type="java.lang.String">
				<column name="login_time"/>
			</property>
		</joined-subclass>
		<filter name="nameFiter" condition="username=:inputName"></filter>
	</class>
	<filter-def name="nameFiter">
		<filter-param name="inputName" type="java.lang.String"/>
	</filter-def>
</hibernate-mapping>

 

 <filter-def name="nameFiter">
<filter-param name="inputName" type="java.lang.String"/>
</filter-def>
定义一个过滤器,名称为nameFiter,filter-param 定义过滤字段的名称,和相应的类型

 

<filter name="nameFiter" condition="username=:inputName"></filter>

对定义的nameFiter的引用,condition="username=:inputName"

username对应表中的字段,inputName是别名

 

以下是一段代码的简单应用

 

	public void list() {
		Session session = null;

		try {
			session = HibernateUtil.getSessionFactory().openSession();
			String hql="from Users where id between 1 and 10";
			session.beginTransaction().begin();
			Query query=session.createQuery(hql);
			Filter filter=session.enableFilter("nameFiter");
			filter.setParameter("inputName", "xxx");
			List<Users> list=query.list();
			Iterator<Users> iter=list.iterator();
			while(iter.hasNext()){
				Users u=iter.next();
				System.out.println("Id: " + u.getId());
				System.out.println("Username: " + u.getUsername());
			}
			session.beginTransaction().commit();
		} catch (HibernateException e) {
			System.out.println(e);
			session.beginTransaction().rollback();
		} finally {
			HibernateUtil.closeSession(session);
		}
	}

 希望对大家有帮助!

 

你可能感兴趣的:(java,Hibernate,xml,.net)