示例代码如下:
1.package com.hb3.pack_01;2.3.import java.util.Iterator;4.import java.util.List;5. 6.import org.hibernate.Query;7.import org.hibernate.Session;8.import org.hibernate.SessionFactory;9.import org.hibernate.Transaction;10.import org.hibernate.cfg.Configuration;11. 12.import com.hb3.pack_01.model.User;13.import com.hb3.pack_01.model.UserBak;14. 15.public class BusinessService {16. 17. public static void main(String[] args) {18.19. Configuration config = new Configuration().configure();20. SessionFactory sessionFactory = config.buildSessionFactory();21. Session session = sessionFactory.openSession();22.23. Query query = session.createQuery("from com.hb3.pack_01.model.User user order by user.age desc, user.name");//[== from User] 24. printUserInfo(query.list());25.26. query = session.createQuery("select new com.hb3.pack_01.model.UserBak(user.name, user.age) from User as user");27. Iterator<?> iterator = query.list().iterator();28. System.out.println("class_name \t\t name/age");29. while (iterator.hasNext()) {30. UserBak userbak = (UserBak) iterator.next();31. System.out.println(userbak.getClz() + " \t " + userbak.getName() + "/" + userbak.getAge());32. }33.34. query = session.createQuery("select upper(user.name) from User as user where (user.age/2 >= ?) and (user.age is not null)");35. query.setInteger(0, 13);36. List<?> names = query.list();37. iterator = names.iterator();38. while(iterator.hasNext()) {39. System.out.println(iterator.next());40. }41.42. query = session.createQuery("select user.name, user.age from User as user where user.age > :minAge");43. query.setInteger("minAge", 25);44. names = query.list();45. iterator = names.iterator();46. while(iterator.hasNext()) {47. Object[] obj = (Object[]) iterator.next();48. System.out.println(obj[0] + "\t" + obj[1]);49. }50.51. query = session.getNamedQuery("com.hb3.pack_01.model.User.QueryUser");52. query.setInteger("minAge", 25);53. printUserInfo(query.list());54.55. Transaction tx= session.beginTransaction();56. query = session.createQuery("update User set age=24 where name='chenyan'");57. query.executeUpdate();58. tx.commit();59. 60. tx= session.beginTransaction();61. query = session.createQuery("delete User where name='yaobin'");62. query.executeUpdate();63. tx.commit();64.65. session.close();66. sessionFactory.close();67. }68.69. public static void printUserInfo(List<?> users){70.71. Iterator<?> iterator = users.iterator();72. System.out.println("id \t name/age");73. while (iterator.hasNext()) {74. User user = (User) iterator.next();75. System.out.println(user.getId() + " \t " + user.getName() + "/" + user.getAge());76. }77. }78.}
以上是小编为您精心准备的的内容,在的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索session
, iterator
, query
, import
, query list
, CreateQuery
user
,以便于您获取更多的相关知识。
时间: 2024-09-20 00:05:19