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();
            }
            
        });
    }

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页