hibernate根据字段去除重复记录

public List<Employee> getUniqueNameByHqlCorrect(){

List<Object[]> list=employeeDao.createQuery("from Employee e inner join (select max(b.id) as id  from  Employee b group by b.name) c on (c.id=e.id)", new Object[]{}).list();

   for(Object[] rows:list){   
System.out.println(": " + rows[0] + "值: " + rows[1]);     
        }  
   return null;
 }


from Employee e inner join (select max(b.id) as id  from  Employee b group by b.name) c on (c.id=e.id)

这条hql会不会写错,为什么会报.异常

org.hibernate.hql.ast.QuerySyntaxException: unexpected token: ( near line 1, column 57 [from com.dhhc.cs.oa.entity.system.Employee e inner join (select max(b.id) as id  from  com.dhhc.cs.oa.entity.system.Employee b group by b.name) c on c.id=e.id]
 at

 

 

 

以下两种方法可以实现根据字段去除重复记录

 

 

/**
  * hibernate sql根据某一字段的值不重复,用in的方法不健壮,效率低,当in里的id值大于1000个报错
  * @return
  */
 public List<Employee> getUniqueNameByHqlCommon(){
  List<Employee> list=employeeDao.createQuery("from Employee e where e.id in(select max(b.id) from  Employee b group by b.name)", new Object[]{}).list();
  for(Employee entity:list){   
   System.out.println(": " +entity.getName() );     
  }  
  return null;
 }

 

 

 

/**
  * 使用联接,相对于in的用法更合适
  * @return
  */
 public List<Employee> getUniqueNameBySqlCorrect(){
  Session session=this.getSessionFactory().openSession();
  String sql="select name,email from sys_employee e inner join (select max(b.id) as id from  sys_employee b group by b.name) c on (c.id=e.id)";
  List<Object[]> list=session.createSQLQuery(sql).list();
  for(Object[] rows:list){   
            System.out.println(": " + rows[0] + "值: " + rows[1]);     
        } 
  session.close();
  return null;
 }




转自:http://www.myexception.cn/software-architecture-design/665519.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值