1. 程式人生 > >Hibernate Criteria 關聯查詢(inner join 與 left join)

Hibernate Criteria 關聯查詢(inner join 與 left join)

實體類 User 、Dept 。 每個User都有對一個Dept屬性

-----------------------------------------------------------model類--------------------------------------------------------------------------

public class User implements Serializable
{
    
    /**
     * 序列化標識id
     */
    private static final long serialVersionUID = 1L;
    
    private Integer id;
    //使用者名稱
    private String userName;
    //密碼
    private String password;
    
    private Dept dept;

   //getter setter

}

 

public class Dept
{
    //id

    private Integer id;
    
    // 部門名字
    private String name;

   //getter setter

}


 --------------------------------------------------------------------Dao(left  join) ---------------------------------------------------------

 /**
     * <Criteria查詢>
     * 
     * @return List
     */
    @SuppressWarnings("unchecked")
    public List<User> findByCriteria()
    {
        return (List)ht.execute(new HibernateCallback()
        {
            
            public Object doInHibernate(Session session)
                throws HibernateException,
                    SQLException
            {
                Criteria criteria = session.createCriteria(User.class);
                criteria.add(Restrictions.eq("password", "123"));
                // 關聯
                criteria.setFetchMode("dept", org.hibernate.FetchMode.JOIN);
                return criteria.list();
            }
            
        });
    }


--------------------------------------------------------------------Dao(inner  join) ---------------------------------------------------------

/**
     * <Criteria查詢>
     * 
     * @return List
     */
    @SuppressWarnings("unchecked")
    public List<User> findByCriteria()
    {
        return (List)ht.execute(new HibernateCallback()
        {
            
            public Object doInHibernate(Session session)
                throws HibernateException,
                    SQLException
            {
                Criteria criteria = session.createCriteria(User.class);
                criteria.add(Restrictions.eq("password", "123"));
                // 關聯
                criteria = criteria.createCriteria("dept");
                criteria.add(Restrictions.eq("name", "Android"));
                return criteria.list();
            }
            
        });
    }