public static void main(String[] args) {
//实例化对象
UserEntity userEntity = new UserEntity();
//配置
Configuration configuration = new Configuration().configure();
//创建会话工厂
SessionFactory sessionFactory = configuration.buildSessionFactory();
//创建会话
Session session = sessionFactory.openSession();
//创建事务
Transaction transaction = session.beginTransaction();
//创建criteriaBuilder
CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
//创建CriteriaQuery
CriteriaQuery<UserEntity> query = criteriaBuilder.createQuery(UserEntity.class);
//定义root
Root<UserEntity> root = query.from(UserEntity.class);
//排序
Order order = criteriaBuilder.desc(root.get("time"));
List<UserEntity> list = session.createQuery(query.groupBy(root.get("userName")).orderBy(order)).getResultList();
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i).getUserName());
}
transaction.commit();
}
hql
```java
public class hqlTest {
public static void main(String[] args) {
Configuration configuration = new Configuration().configure();
SessionFactory sessionFactory = configuration.buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction =session.beginTransaction();
UserEntity userEntity = new UserEntity();
Query<UserEntity> query = session.createQuery(" from UserEntity u group by userName order by time");
List<UserEntity> list = query.getResultList();
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i).getUserName());
}
}
}