1.表结构
2.HQL连接查询
Hibernate支持的连接有:
inner join
left outer join
right outer join
inner join只能得到满足连接条件的记录,左右表交换位置,结果不变。
left join 左表中的数据必须出现在结果集中,哪怕不满足连接条件。
right join 右表中的数据必须出现在结果集中,哪怕不满足连接条件。
3.实体类
1 package cn.yunhe.entity; 2 3 import javax.persistence.*; 4 import java.util.HashSet; 5 import java.util.Set; 6 7 @Entity 8 @Table(name = "users") 9 public class Users { 10 private int id; 11 private String loginId; 12 private String loginPwd; 13 private String name; 14 private int age; 15 private String phone; 16 private Set<Orders> orders= new HashSet<Orders>(); 17 18 @Id 19 @GeneratedValue 20 @Column(name = "id") 21 public int getId() { 22 return id; 23 } 24 25 public void setId(int id) { 26 this.id = id; 27 } 28 29 @Column(name = "loginId") 30 public String getLoginId() { 31 return loginId; 32 } 33 34 public void setLoginId(String loginId) { 35 this.loginId = loginId; 36 } 37 38 @Column(name = "loginPwd") 39 public String getLoginPwd() { 40 return loginPwd; 41 } 42 43 public void setLoginPwd(String loginPwd) { 44 this.loginPwd = loginPwd; 45 } 46 47 @Column(name = "name") 48 public String getName() { 49 return name; 50 } 51 52 public void setName(String name) { 53 this.name = name; 54 } 55 56 @Column(name = "age") 57 public int getAge() { 58 return age; 59 } 60 61 public void setAge(int age) { 62 this.age = age; 63 } 64 65 @Column(name = "phone") 66 public String getPhone() { 67 return phone; 68 } 69 70 public void setPhone(String phone) { 71 this.phone = phone; 72 } 73 74 @OneToMany(cascade = CascadeType.ALL,fetch = FetchType.LAZY,mappedBy = "users")//双向时不要@JoinColumn 75 //@JoinColumn(name = "userid") 76 public Set<Orders> getOrders() { 77 return orders; 78 } 79 80 public void setOrders(Set<Orders> orders) { 81 this.orders = orders; 82 } 83 }
1 package cn.yunhe.entity; 2 3 import javax.persistence.*; 4 import java.util.Date; 5 6 /** 7 * Created by Administrator on 2017/7/11. 8 */ 9 @Entity 10 @Table(name = "orders") 11 public class Orders { 12 private int id; 13 private Date orderDate; 14 private double totalPrice; 15 private Users users; 16 17 @Id 18 @GeneratedValue 19 @Column(name = "id") 20 public int getId() { 21 return id; 22 } 23 24 public void setId(int id) { 25 this.id = id; 26 } 27 28 @Column(name = "orderDate") 29 public Date getOrderDate() { 30 return orderDate; 31 } 32 33 public void setOrderDate(Date orderDate) { 34 this.orderDate = orderDate; 35 } 36 37 @Column(name = "totalPrice") 38 public double getTotalPrice() { 39 return totalPrice; 40 } 41 42 public void setTotalPrice(double totalPrice) { 43 this.totalPrice = totalPrice; 44 } 45 46 @ManyToOne(fetch = FetchType.EAGER) 47 @JoinColumn(name = "userid") 48 public Users getUsers() { 49 return users; 50 } 51 52 public void setUsers(Users users) { 53 this.users = users; 54 } 55 }
4.配置文件
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE hibernate-configuration 3 PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" 4 "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> 5 <hibernate-configuration> 6 <session-factory> 7 <!--正向工程(自动建表)--> 8 <property name="hbm2ddl.auto">update</property> 9 <!--数据库方言--> 10 <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> 11 <property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property> 12 <property name="connection.driver_class">com.mysql.jdbc.Driver</property> 13 <property name="connection.username">root</property> 14 <property name="connection.password">1234</property> 15 <!--显示sql语句--> 16 <property name="show_sql">true</property> 17 18 <mapping class="cn.yunhe.entity.Users"/> 19 <mapping class="cn.yunhe.entity.Orders"/> 20 21 </session-factory> 22 </hibernate-configuration>
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 3 <modelVersion>4.0.0</modelVersion> 4 <groupId>cn.yunhe</groupId> 5 <artifactId>hibernate5</artifactId> 6 <packaging>war</packaging> 7 <version>1.0-SNAPSHOT</version> 8 <name>hibernate5 Maven Webapp</name> 9 <url>http://maven.apache.org</url> 10 <dependencies> 11 <dependency> 12 <groupId>junit</groupId> 13 <artifactId>junit</artifactId> 14 <version>4.12</version> 15 <scope>test</scope> 16 </dependency> 17 18 <dependency> 19 <groupId>javax.servlet</groupId> 20 <artifactId>javax.servlet-api</artifactId> 21 <version>3.1.0</version> 22 <scope>provided</scope> 23 </dependency> 24 25 <dependency> 26 <groupId>mysql</groupId> 27 <artifactId>mysql-connector-java</artifactId> 28 <version>5.1.6</version> 29 </dependency> 30 31 <dependency> 32 <groupId>org.apache.struts</groupId> 33 <artifactId>struts2-core</artifactId> 34 <version>2.3.31</version> 35 </dependency> 36 37 <dependency> 38 <groupId>javax.servlet</groupId> 39 <artifactId>jstl</artifactId> 40 <version>1.2</version> 41 </dependency> 42 43 <dependency> 44 <groupId>org.apache.struts</groupId> 45 <artifactId>struts2-dojo-plugin</artifactId> 46 <version>2.3.16</version> 47 </dependency> 48 49 <dependency> 50 <groupId>org.hibernate</groupId> 51 <artifactId>hibernate-core</artifactId> 52 <version>3.5.0-Final</version> 53 </dependency> 54 55 <dependency> 56 <groupId>org.hibernate</groupId> 57 <artifactId>hibernate-annotations</artifactId> 58 <version>3.5.0-Final</version> 59 </dependency> 60 <dependency> 61 <groupId>org.slf4j</groupId> 62 <artifactId>slf4j-log4j12</artifactId> 63 <version>1.5.8</version> 64 </dependency> 65 66 <dependency> 67 <groupId>org.javassist</groupId> 68 <artifactId>javassist</artifactId> 69 <version>3.13.0-GA</version> 70 </dependency> 71 </dependencies> 72 <build> 73 <finalName>hibernate5</finalName> 74 </build> 75 </project>
5.测试类
1 package cn.yunhe.Demo; 2 3 import cn.yunhe.entity.Books; 4 import cn.yunhe.entity.Orders; 5 import cn.yunhe.entity.Publishers; 6 import cn.yunhe.entity.Users; 7 import org.hibernate.Criteria; 8 import org.hibernate.Query; 9 import org.hibernate.Session; 10 import org.hibernate.Transaction; 11 import org.hibernate.cfg.AnnotationConfiguration; 12 import org.hibernate.cfg.Configuration; 13 import org.hibernate.criterion.Order; 14 import org.hibernate.criterion.Projections; 15 import org.hibernate.criterion.Restrictions; 16 import org.junit.After; 17 import org.junit.Before; 18 import org.junit.Test; 19 20 import java.util.List; 21 22 /** 23 * Created by Administrator on 2017/7/11. 24 */ 25 public class Demo { 26 Session session=null; 27 Transaction tr=null; 28 29 @Before 30 public void init(){ 31 Configuration config =new AnnotationConfiguration().configure(); 32 session= config.buildSessionFactory().openSession(); 33 tr=session.beginTransaction(); 34 } 35 36 @Test //Hibernate内链接 查询订单中的用户的信息 37 public void test1(){ 38 String hql="select o.users from Orders o where o.id=1"; 39 Query query=session.createQuery(hql); 40 List<Users> list= query.list(); 41 session.close();//关闭也可以查出来 42 Users user=list.get(0); 43 System.out.println(user.getName()); 44 } 45 46 @Test //Hibernate内链接 使用交叉连接查询 47 public void test2(){ 48 String hql="select u from Users u,Orders o where u=o.users and o.id=3"; 49 List<Users> list= session.createQuery(hql).list(); 50 for (Users users:list){ 51 System.out.println(users.getName()); 52 } 53 } 54 55 @Test//Hibernate内链接 查询所有购买过书籍的用户,采用子查询 56 public void test3(){ 57 String hql="select u from Users u where u in(select o.users from Orders o)";//子查询 58 //String hql="select distinct u from Users u inner join u.orders";//内连接 59 List<Users> list =session.createQuery(hql).list(); 60 for (Users users:list){ 61 System.out.println(users.getName()); 62 } 63 } 64 65 @Test//Hibernate内链接 抓取内链接 66 public void test4(){ 67 String hql="select distinct u from Users u inner join u.orders"; 68 List<Users> list= session.createQuery(hql).list(); 69 session.close();//关闭session 70 for (Users users:list){ 71 System.out.println(users.getName()+"的订单:"); 72 for (Orders orders:users.getOrders()){ 73 System.out.println(orders.getId()+" "+orders.getTotalPrice()); 74 } 75 } 76 } 77 78 @Test//Hibernate外链接 left outer join(左外链接) 79 //查询没有任何订单的用户 80 //left join中也可以使用fetch,即:left join fetch,表示是否填充左边(Users)中的集合属性 81 public void test5(){ 82 String hql="select u from Users u left join u.orders o where o is null"; 83 List<Users> list= session.createQuery(hql).list(); 84 for (Users users:list){ 85 System.out.println(users.getName()); 86 } 87 } 88 89 @Test//本地查询 原生SQL语句查询 session.createSQLQuery()方法 90 public void test6(){ 91 String sql="select * from users"; 92 Query query=session.createSQLQuery(sql); 93 List<Object[]> list= query.list(); 94 for (Object[] objects :list){ 95 System.out.println(objects[1]); 96 } 97 } 98 99 @Test//本地查询 原生sql语句查询 使用占位符 100 /*说明:查询指定了 SQL查询语句,带一个占位符,可以让Hibernate使用字段的别名 101 . 查询返回的实体,和它的SQL表的别名. addEntity()方法将SQL表的别名和实体类联 102 系起来。 103 * */ 104 public void test7(){ 105 String sql="select {u.*},{o.*} from users u,orders o where u.id=o.userid"; 106 Query query=session.createSQLQuery(sql).addEntity("u",Users.class).addEntity("o",Orders.class); 107 List<Object[]> list= query.list(); 108 for (Object[] objects:list){ 109 Users users= (Users) objects[0]; 110 Orders orders= (Orders) objects[1]; 111 System.out.println("用户名:"+users.getName()+",订单价格"+orders.getTotalPrice()); 112 } 113 } 114 115 @Test //Criteria查询 使用Criteria查询所有的用户 116 public void test8(){ 117 Criteria criteria=session.createCriteria(Users.class); 118 List<Users> list= criteria.list(); 119 for (Users users:list){ 120 System.out.println(users.getName()); 121 } 122 } 123 124 @Test//Criteria查询 条件查询 125 //使用Restrictions中的静态方法来构造查询条件,然后“add”到Criteria中 126 //查询出年龄大于400的用户 127 public void test9(){ 128 Criteria criteria=session.createCriteria(Users.class); 129 List<Users> list= criteria.add(Restrictions.gt("age",400)).list(); 130 for (Users users:list){ 131 System.out.println(users.getName()+",age:"+users.getAge()); 132 } 133 134 } 135 136 @Test//Criteria查询 排序 根据年龄进行降序排列 137 public void test10(){ 138 Criteria criteria=session.createCriteria(Users.class); 139 List<Users> list= criteria.addOrder(Order.desc("age")).list(); 140 for (Users users:list){ 141 System.out.println(users.getName()+",age:"+users.getAge()); 142 } 143 } 144 145 @Test//Criteria查询 分页 146 // setFirstResult方法设置开始位置 147 // setMaxResult方法设置页大小 148 public void test11(){ 149 Criteria criteria=session.createCriteria(Users.class); 150 List<Users> list= criteria.setFirstResult(2).setMaxResults(3).list(); 151 for (Users users:list){ 152 System.out.println(users.getName()+",age:"+users.getAge()); 153 } 154 } 155 156 @Test// Criteria查询 使用聚合函数 使用Criteria 的setProjection 方法设置统计列 max min avg sum 等用法相同 157 public void test12(){ 158 Criteria criteria=session.createCriteria(Users.class); 159 criteria.setProjection(Projections.avg("age")); 160 Double age= (Double) criteria.uniqueResult(); 161 System.out.println("员工的平均年龄是:"+age); 162 } 163 164 @Test//Criteria查询 连接查询 165 //使用createCriteria() 方法非常容易地在互相关联的实体间进行连接查询 166 //查询孙权的订单信息,要求订单总价在300以上。 167 public void test13(){ 168 Criteria c_orders=session.createCriteria(Orders.class); 169 Criteria c_users=c_orders.createCriteria("users");//两表关联,这步最重要 170 c_orders.add(Restrictions.gt("totalPrice",300d));//double类型后面要加d 不然会报无法将integer转换为double 171 c_users.add(Restrictions.eq("id",1)); 172 List<Orders> list= c_orders.list(); 173 for (Orders orders:list){ 174 System.out.println("客户名称:"+orders.getUsers().getName()+" 订单总价:"+orders.getTotalPrice()); 175 } 176 } 177 178 @After 179 public void down(){ 180 session.close(); 181 } 182 183 }
6.HQL优化