工具類:
1 public class H3Util { 2 3 private static final SessionFactory sessionFactory = buildSessionFactory(); 4 5 private static SessionFactory buildSessionFactory() { 6 try { 7 //從類加載路徑中讀取hibernate.cfg.xml文件生成SessionFactory對象 8 return new Configuration().configure().buildSessionFactory(); 9 } catch (Throwable ex) { 10 System.err.println("Initial SessionFactory creation failed." + ex); 11 throw new ExceptionInInitializerError(ex); 12 } 13 } 14 15 public static SessionFactory getSessionFactory() { 16 return sessionFactory; 17 } 18 }View Code
基礎的增刪改查:
1 public class TestHibernate { 2 3 @Test 4 public void add() { 5 SessionFactory sessionFactory = H3Util.getSessionFactory(); 6 Session session = sessionFactory.openSession(); 7 Transaction transaction = session.beginTransaction(); 8 for (int i = 0; i < 20; i++) { 9 session.save(new User(null, "test"+i, "123456", new Date(), 1, 1000.0f)); 10 } 11 transaction.commit(); 12 session.close(); 13 System.out.println("成功"); 14 } 15 16 @Test 17 public void find() { 18 SessionFactory sessionFactory = H3Util.getSessionFactory(); 19 Session session = sessionFactory.openSession(); 20 System.out.println("+++++++++"); 21 User user = (User)session.get(User.class, 1); 22 System.out.println("======"); 23 System.out.println(user); 24 session.close(); 25 } 26 27 @Test 28 public void del() { 29 SessionFactory sessionFactory = H3Util.getSessionFactory(); 30 Session session = sessionFactory.openSession(); 31 Transaction transaction = session.beginTransaction(); 32 User user = (User)session.get(User.class, 2); 33 session.delete(user); 34 transaction.commit(); 35 session.close(); 36 System.out.println("成功"+user); 37 } 38 39 @Test 40 public void update() { 41 SessionFactory sessionFactory = H3Util.getSessionFactory(); 42 Session session = sessionFactory.openSession(); 43 Transaction transaction = session.beginTransaction(); 44 User user = (User)session.get(User.class, 1); 45 user.setPassword("111111"); 46 session.update(user); 47 transaction.commit(); 48 session.close(); 49 System.out.println("成功"+user); 50 } 51 52 @Test 53 public void findList() { 54 SessionFactory sessionFactory = H3Util.getSessionFactory(); 55 Session session = sessionFactory.openSession(); 56 String hql = "from User"; 57 Query query = session.createQuery(hql); 58 @SuppressWarnings("unchecked") 59 List<User> uList = query.list(); 60 for (User user : uList) { 61 System.out.println(user); 62 } 63 session.close(); 64 } 65 66 }View Code
測試hibernate的對象狀態:
1 /** 2 * @author nunu 3 * 測試 hibernate 對象 4 */ 5 public class TestHibernateObject { 6 7 /** 8 * 共有三種狀態: 9 * 1、瞬時對象:TO 直接new對象 10 * 特點: 11 * 1、不受hibernate管理(session管理) 12 * 2、沒有OID 13 * 2、持久化對象:PO 14 * 特點: 15 * 1、受hibernate管理(session管理) 16 * 2、有OID 17 * 3、離線(托管)對象:DO 18 * 特點: 19 * 1、曾經受過hibernate管理,現在不受管理的(session) 20 * 2、有OID 21 */ 22 @Test 23 public void status(){ 24 SessionFactory sf = H3Util.getSessionFactory(); 25 Session session = sf.openSession(); 26 Transaction ts = session.beginTransaction(); 27 //user --> TO 28 User user = new User(null, "nnn", "1234568", new Date(), 0, 999.9f); 29 session.save(user); 30 ts.commit(); 31 //session.close(); 32 //user --> PO 33 System.out.println(user); 34 session.delete(user); 35 //user --> DO 36 System.out.println(user+"----"); 37 } 38 39 40 /** 41 * session 中數據發生更改,若事務提交,數據庫中數據修改 42 * 若事務不提交,session關閉時,不會修改數據庫 43 */ 44 @Test 45 public void addUser() { 46 SessionFactory sf = H3Util.getSessionFactory(); 47 Session session = sf.openSession(); 48 Transaction ts = session.beginTransaction(); 49 /** 50 * PO:持久化對象--數據庫表中的記錄同步的對象,只要該對象發生任何改變,session關閉時都會同步該對象的狀態到數據庫中的表記錄上 51 User user = (User) session.get(User.class, "4028810d57c20db20157c20db5920013"); 52 user.setUsername("wangwu"); 53 */ 54 55 //DO 56 //User user = new User("4028408157c0f5920157c0f593e100001", "wangwu", "12312", new SimpleDateFormat("yyyy-MM-dd").parse("2016-10-14"), 1, 1000.0f); 57 //user.setUsername("wangwu"); 58 59 //DO--PO :session -->一定會發生sql語句 60 //session.update(user); 61 62 //PO 63 User user = (User) session.get(User.class, "4028810d57c20db20157c20db5920013"); 64 65 //PO--TO 66 session.delete(user); 67 68 /** 69 * 若不提交事務不會進行數據庫修改 70 */ 71 ts.commit(); 72 //session會拿session中的所有的持久化對象和 73 session.close(); 74 75 System.out.println(user); 76 } 77 }View Code
hibernate的一級緩存:
1 /** 2 * @author nunu 3 * 一級緩存 4 */ 5 public class TestHibernateSession { 6 7 /** 8 * 查詢結果會放入session中,從session中獲取結果不需要查詢語句 9 */ 10 @Test 11 public void sessionQuery() { 12 SessionFactory sf = H3Util.getSessionFactory(); 13 Session session = sf.openSession(); 14 15 //默認所有查詢,都會將結果存入到一級緩存(session) 16 //HQL、QBC、原生SQL查找:每次都會發送新sql,不會去session中獲取 17 Query query = session.createQuery("from User where userId = '4028810d57c20db20157c20db58c000e'"); 18 User user = (User)query.uniqueResult(); 19 20 Query query1 = session.createQuery("from User where userId = 'ff80808157c72cbe0157c72cc1540000'"); 21 User user1 = (User)query1.uniqueResult(); 22 System.out.println("0"+user); 23 System.out.println("1"+user1); 24 User user2 = (User)session.get(User.class,"4028810d57c20db20157c20db58c000e"); 25 //user2的獲取不會發出查詢語句 26 System.out.println("2"+user2); 27 session.close(); 28 } 29 30 31 /** 32 * 不發出update方法,修改session中結果是,再次獲取的該值是修改過的結果 33 * 34 * 先去session緩存(一級緩存)查詢看有沒對應的對象 35 * 如果沒有就會立即(無論有沒有使用到該對象)發生sql語句去數據庫查找, 36 * 查詢到之後會將查詢結果再存入到session緩存(一級緩存中) 37 */ 38 @Test 39 public void testSessionUpdate() { 40 SessionFactory sf = H3Util.getSessionFactory(); 41 Session session = sf.openSession(); 42 User user = (User)session.get(User.class,"4028810d57c20db20157c20db5920013"); 43 44 user.setUsername("admin"); 45 46 //不會發送sql語句: 47 //User user1 = (User)session.get(User.class,"4028810d57c20db20157c20db5920013"); 48 //System.out.println(user1); 49 //獲取到是最新的對象信息 50 //System.out.println(user1.getUsername()); 51 52 session.close(); 53 } 54 55 56 /** 57 * 懶加載 58 * org.hibernate.LazyInitializationException: could not initialize proxy - no Session 59 * 先去session緩存(一級緩存)查詢看有沒對應的對象 60 * 如果沒有,再看程序中有沒有使用改對象到除OID之外的屬性,如果只是使用了OID它不會發送任何sql語句 61 * 但是如果使用除OID之外的屬性,此時(使用之前)才會發送sql語句查詢 62 */ 63 @Test 64 public void testLoad() { 65 SessionFactory sf = H3Util.getSessionFactory(); 66 Session session = sf.openSession(); 67 User user1 = (User) session.load(User.class, "4028810d57c20db20157c20db5920013"); 68 User user2 = (User) session.load(User.class, "ff80808157c72cbe0157c72cc1540000"); 69 System.out.println("--------------"); 70 71 System.out.println(user1); 72 System.out.println(user2); 73 74 session.close(); 75 76 //發送:sql 77 //System.out.println(user.getUsername()); 78 79 //System.out.println(user1.getUsername()); 80 } 81 }View Code
hibernate的模糊查詢、單條記錄查詢、分頁查詢、、等單表基本查詢
1 public class TestQuery { 2 @Test 3 public void list() { 4 SessionFactory sessionFactory = H3Util.getSessionFactory(); 5 Session session = sessionFactory.openSession(); 6 String hql = "from User"; 7 Query query = session.createQuery(hql); 8 @SuppressWarnings("unchecked") 9 List<User> uList = query.list(); 10 for (User user : uList) { 11 System.out.println(user); 12 } 13 session.close(); 14 } 15 16 /** 17 * 模糊查詢 18 */ 19 @Test 20 public void list1() { 21 SessionFactory sessionFactory = H3Util.getSessionFactory(); 22 Session session = sessionFactory.openSession(); 23 String hql = "from User as u where u.username like :username"; 24 Query query = session.createQuery(hql); 25 query.setString("username", "%test1%"); 26 @SuppressWarnings("unchecked") 27 List<User> uList = query.list(); 28 for (User user : uList) { 29 System.out.println(user); 30 } 31 session.close(); 32 } 33 34 /** 35 * 模糊查詢 36 */ 37 @Test 38 public void list2() { 39 SessionFactory sessionFactory = H3Util.getSessionFactory(); 40 Session session = sessionFactory.openSession(); 41 String hql = "from User as u where u.username like ?"; 42 Query query = session.createQuery(hql); 43 query.setString(0, "%test1%"); 44 @SuppressWarnings("unchecked") 45 List<User> uList = query.list(); 46 for (User user : uList) { 47 System.out.println(user); 48 } 49 session.close(); 50 } 51 52 /** 53 * 單個記錄查詢 54 */ 55 @Test 56 public void uniqueResult() { 57 SessionFactory sessionFactory = H3Util.getSessionFactory(); 58 Session session = sessionFactory.openSession(); 59 String hql = "from User where userId = '4028810d57c20db20157c20db58c000a'"; 60 Query query = session.createQuery(hql); 61 User u = (User) query.uniqueResult(); 62 System.out.println(u); 63 session.close(); 64 } 65 //findUsername 66 @Test 67 public void findUsername() { 68 SessionFactory sessionFactory = H3Util.getSessionFactory(); 69 Session session = sessionFactory.openSession(); 70 String hql = "select username from User"; 71 Query query = session.createQuery(hql); 72 @SuppressWarnings("unchecked") 73 List<String> names = query.list(); 74 for (String string : names) { 75 System.out.println("==="+string); 76 } 77 session.close(); 78 } 79 80 81 @Test//查詢多個屬性(投影) 82 public void findUsernameAndId(){ 83 SessionFactory sf = H3Util.getSessionFactory(); 84 Session session = sf.openSession(); 85 86 //sql:select username,sex from t_user 87 //String hql = "select sex,username from User where userId = '4028408157bbe02f0157bbe030820000' "; 88 //Query query = session.createQuery(hql); 89 90 //返回值至多有一個:多了就會報異常 org.hibernate.NonUniqueResultException: query did not return a unique result: 2 91 /*Object[] obj = (Object[]) query.uniqueResult(); 92 93 System.out.println("sex"+obj[0]); 94 System.out.println("username"+obj[1]);*/ 95 96 //將查詢結果封裝到對象中:提供大量的構造方法 97 String hql = "select new User(userId,username) from User where userId = '4028810d57c20db20157c20db58b0005' "; 98 Query query = session.createQuery(hql); 99 User user = (User)query.uniqueResult(); 100 101 System.out.println(user); 102 } 103 104 /** 105 * 分頁查詢 106 */ 107 @Test 108 public void findByPage() { 109 SessionFactory sf = H3Util.getSessionFactory(); 110 Session session = sf.openSession(); 111 112 113 int currentPage = 2; 114 int pageSize = 3; 115 String hql = "from User"; 116 Query query = session.createQuery(hql); 117 query.setFirstResult((currentPage-1)*pageSize); 118 query.setMaxResults(pageSize); 119 @SuppressWarnings("unchecked") 120 List<User> uList = query.list(); 121 for (User user : uList) { 122 System.out.println(user); 123 } 124 session.close(); 125 } 126 127 128 @Test//固定條件查詢:查詢username = 李四 129 public void findByUsername(){ 130 SessionFactory sf = H3Util.getSessionFactory(); 131 Session session = sf.openSession(); 132 String hql = "from User where username = '李四'"; 133 Query query = session.createQuery(hql); 134 @SuppressWarnings("unchecked") 135 List<User> list = query.list(); 136 for (User user : list) { 137 System.out.println(user); 138 } 139 } 140 @Test//可變參條件查詢:查詢username = 李四 141 public void findByUsername1(){ 142 String username = "李四"; 143 int sex = 1; 144 float salary = 10000.0f; 145 SessionFactory sf = H3Util.getSessionFactory(); 146 Session session = sf.openSession(); 147 //String hql = "from User where sex = ? and username = ? and salary = ?"; 148 //Query query = session.createQuery(hql); 149 //為?設置具體數值 150 //只能使用索引方式設置值:此形式參數傳遞索引,靈活度太差,不推薦使用 151 //query.setString(0, username); 152 //query.setInteger(1, sex); 153 //query.setFloat(2, salary); 154 155 156 //使用:別名 占位符形式 157 //使用屬性名(占位符)方式設置值(推薦):名稱和:後面的一致 158 String hql = "from User where sex = :sex and username = :username and salary = :salary"; 159 Query query = session.createQuery(hql); 160 query.setString("username", username); 161 query.setInteger("sex", sex); 162 //query.setFloat("salary", salary); 163 query.setParameter("salary", salary);//如果不確定類型可以使用該方式,不推薦使用 164 165 @SuppressWarnings("unchecked") 166 List<User> list = query.list(); 167 for (User user : list) { 168 System.out.println(user); 169 } 170 } 171 172 @Test//統計記錄個數 173 public void findCount(){ 174 SessionFactory sf = H3Util.getSessionFactory(); 175 Session session = sf.openSession(); 176 String hql = "select count(*) from User"; 177 Query query = session.createQuery(hql); 178 179 Long count = (Long) query.uniqueResult(); 180 System.out.println(count); 181 } 182 183 @Test//最小值 184 public void findMin(){ 185 SessionFactory sf = H3Util.getSessionFactory(); 186 Session session = sf.openSession(); 187 //返回值:和字段類型一致 188 String hql = "select min(salary) from User"; 189 Query query = session.createQuery(hql); 190 191 Float min = (Float) query.uniqueResult(); 192 System.out.println(min); 193 } 194 195 @Test//求和 196 public void findSum(){ 197 SessionFactory sf = H3Util.getSessionFactory(); 198 Session session = sf.openSession(); 199 //返回值:整形Long/小數Double 200 String hql = "select sum(salary) from User"; 201 Query query = session.createQuery(hql); 202 203 Double sum = (Double) query.uniqueResult(); 204 System.out.println(sum); 205 } 206 @Test//求平均值 207 public void findAvg(){ 208 SessionFactory sf = H3Util.getSessionFactory(); 209 Session session = sf.openSession(); 210 //返回值:Double 211 String hql = "select avg(salary) from User"; 212 Query query = session.createQuery(hql); 213 214 Double avg = (Double) query.uniqueResult(); 215 System.out.println(avg); 216 } 217 218 @Test//求分組查找 219 public void findGroup(){ 220 SessionFactory sf = H3Util.getSessionFactory(); 221 Session session = sf.openSession(); 222 String hql = "select sex, count(*) from User group by sex"; 223 Query query = session.createQuery(hql); 224 @SuppressWarnings("unchecked") 225 List<Object[]> list = query.list(); 226 for (int i=0;i<list.size();i++) { 227 System.out.println(list.get(i)[0]+":"+list.get(i)[1]); 228 } 229 } 230 @Test//求排序 231 public void findOrder(){ 232 SessionFactory sf = H3Util.getSessionFactory(); 233 Session session = sf.openSession(); 234 String hql = "from User order by salary asc,sex asc"; 235 Query query = session.createQuery(hql); 236 @SuppressWarnings("unchecked") 237 List<User> list = query.list(); 238 for (User user : list) { 239 System.out.println(user); 240 } 241 } 242 @Test//求排序 243 public void findOrder1(){ 244 SessionFactory sf = H3Util.getSessionFactory(); 245 Session session = sf.openSession(); 246 Query query = session.getNamedQuery("findOrder"); 247 @SuppressWarnings("unchecked") 248 List<User> list = query.list(); 249 for (User user : list) { 250 System.out.println(user); 251 } 252 } 253 }View Code
hibernate的QBC:query by criteria
1 /** 2 * @author nunu 3 * QBC:query by criteria 4 */ 5 public class TestCriteria { 6 7 /** 8 * criteria 普通查詢 9 */ 10 @Test 11 public void list(){ 12 SessionFactory sf = H3Util.getSessionFactory(); 13 Session session = sf.openSession(); 14 Criteria criteria = session.createCriteria(User.class); 15 @SuppressWarnings("unchecked") 16 List<User> uList = criteria.list(); 17 for (User user : uList) { 18 System.out.println(user); 19 } 20 } 21 22 /** 23 * 查詢用戶名 24 */ 25 @Test 26 public void findUsername(){ 27 SessionFactory sf = H3Util.getSessionFactory(); 28 Session session = sf.openSession(); 29 //select username from User 30 Criteria criteria = session.createCriteria(User.class); 31 //准備投影(屬性) 32 Property prop = Property.forName("username"); 33 //設置投影(屬性) 34 criteria.setProjection(prop); 35 36 @SuppressWarnings("unchecked") 37 List<String> usernames = criteria.list(); 38 for (String name : usernames) { 39 System.out.println(name); 40 } 41 } 42 43 44 /** 45 * 查詢用戶名和性別 46 */ 47 @Test 48 public void findUsernameSex(){ 49 SessionFactory sf = H3Util.getSessionFactory(); 50 Session session = sf.openSession(); 51 //select username from User 52 Criteria criteria = session.createCriteria(User.class); 53 //准備投影(屬性) 54 Property prop1 = Property.forName("username"); 55 Property prop2 = Property.forName("sex"); 56 57 //獲取投影集合 58 ProjectionList pList = Projections.projectionList(); 59 pList.add(prop1); 60 pList.add(prop2); 61 //設置投影(屬性) 62 criteria.setProjection(pList); 63 64 @SuppressWarnings("unchecked") 65 List<Object[]> usernames = criteria.list(); 66 for (int i = 0; i < usernames.size(); i++) { 67 System.out.println(usernames.get(i)[0]+":"+usernames.get(i)[1]);; 68 } 69 } 70 71 /** 72 * 模糊查詢 73 */ 74 @Test 75 public void findByName(){ 76 SessionFactory sf = H3Util.getSessionFactory(); 77 Session session = sf.openSession(); 78 //select username from User where username = :name 79 Criteria criteria = session.createCriteria(User.class); 80 //添加條件 81 //criteria.add(Restrictions.eq("username", "李四")); 82 criteria.add(Restrictions.like("username", "%test1%")); 83 84 @SuppressWarnings("unchecked") 85 List<User> list = criteria.list(); 86 for (User user : list) { 87 System.out.println(user); 88 } 89 } 90 @Test 91 public void findGroup(){ 92 SessionFactory sf = H3Util.getSessionFactory(); 93 Session session = sf.openSession(); 94 //select username from User group by sex 95 Criteria criteria = session.createCriteria(User.class); 96 97 Projection p1 = Projections.groupProperty("sex"); 98 Projection p2 = Projections.rowCount();//count(*) 99 100 ProjectionList pList = Projections.projectionList(); 101 pList.add(p1); 102 pList.add(p2); 103 //分組 104 criteria.setProjection(pList); 105 @SuppressWarnings("unchecked") 106 List<Object[]> list = criteria.list(); 107 108 for (int i = 0; i < list.size(); i++) { 109 System.out.println(list.get(i)[0]+":"+list.get(i)[1]); 110 } 111 } 112 }View Code
hibernate 中使用SQL語句查詢
1 /** 2 * @author nunu 3 * hibernate 中使用SQL語句查詢 4 */ 5 public class TestSQLQuery { 6 7 @Test 8 public void testList() { 9 SessionFactory sf = H3Util.getSessionFactory(); 10 Session session = sf.openSession(); 11 String sql = "select * from t_user"; 12 SQLQuery sqlQuery = session.createSQLQuery(sql); 13 @SuppressWarnings("unchecked") 14 List<Object[]> uList = sqlQuery.list(); 15 for (Object[] user : uList) { 16 for (int i = 0; i < user.length; i++) { 17 System.out.println(user[i]); 18 } 19 } 20 } 21 22 23 @Test 24 public void testList1() { 25 SessionFactory sf = H3Util.getSessionFactory(); 26 Session session = sf.openSession(); 27 String sql = "select * from t_user"; 28 SQLQuery sqlQuery = session.createSQLQuery(sql); 29 //告訴系統如何去封裝對象 30 sqlQuery.addEntity(User.class); 31 @SuppressWarnings("unchecked") 32 List<User> uList = sqlQuery.list(); 33 for (User user : uList) { 34 System.out.println(user); 35 } 36 } 37 38 /** 39 * 指明對象 40 */ 41 @Test 42 public void testList2() { 43 SessionFactory sf = H3Util.getSessionFactory(); 44 Session session = sf.openSession(); 45 String sql = "select u.* from t_user u"; 46 SQLQuery sqlQuery = session.createSQLQuery(sql); 47 //告訴系統如何去封裝對象 48 sqlQuery.addEntity("u",User.class); 49 @SuppressWarnings("unchecked") 50 List<User> uList = sqlQuery.list(); 51 for (User user : uList) { 52 System.out.println(user); 53 } 54 } 55 }View Code