google Analytics

Monday, July 26, 2010

HIbernate Filter Example

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping
   PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
   "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
  <class name="com.hibernatebook.filters.User">
    <id name="id" type="int">
      <generator class="native"/>
    </id>
    <property name="username" type="string" length="32"/>
    <property name="activated" type="boolean"/>
    <filter name="activatedFilter" condition=":activatedParam = activated"/>
  </class>
  <filter-def name="activatedFilter">
    <filter-param name="activatedParam" type="boolean"/>
  </filter-def>
</hibernate-mapping>


public class SimpleFilterExample
{
public static void main (String args[])
{
Session session = HibernateHelper.getSession();

//insert the users
insertUser("ray",true,session);
insertUser("jason",true,session);
insertUser("beth",false,session);
insertUser("judy",false,session);
insertUser("rob",false,session);

//Show all users
System.out.println("===ALL USERS===");
displayUsers(session);

//Show activated users
Filter filter = session.enableFilter("activatedFilter");
filter.setParameter("activatedParam",new Boolean(true));
System.out.println("===ACTIVATED USERS===");
displayUsers(session);

//Show non-activated users
filter.setParameter("activatedParam",new Boolean(false));
System.out.println("===NON-ACTIVATED USERS===");
displayUsers(session);

session.close();
}

public static void displayUsers(Session session)
{
Transaction trans = session.beginTransaction();
Query query = session.createQuery("from User");
Iterator results = query.iterate();
while (results.hasNext())
{
User user = (User) results.next();
System.out.print(user.getUsername() + " is ");
if (user.isActivated())
{
System.out.println("activated.");
}
else
{
System.out.println("not activated.");
}
}
trans.commit();
}
public static void insertUser(String name, boolean activated, Session session)
{
Transaction trans = session.beginTransaction();
User user = new User();
user.setUsername(name);
user.setActivated(activated);
session.save(user);
trans.commit();
}
}

No comments:

Post a Comment