hibernate的基础学习
工具类:
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 }
基础的增删改查:
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 }
测试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 }
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 }
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 }
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 }
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 }