什么是Hibernate框架
1.Hibernate持久层框架
2.Hibernate是一个开源的对象映射框架
3.hibernate可以实现数据库中表和实体类对象的映射关系,自动生成sql语句并执行(全自动)
4.Hibernate是一个全自动(自动生成sql)的持久层框架,可以采用面向对象的方式来对数据库进行CRUD操作
SSH框架
框架自由的组合使用
spring
struts2|springMVC
hibernate|mybatis|JPA
Hibernate执行流程
Hibernate的使用
1.导入依赖包
<dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.0.6.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-ehcache</artifactId> <version>5.0.6.Final</version> </dependency> <dependency> <groupId>javax.transaction</groupId> <artifactId>jta</artifactId> <version>1.1</version> </dependency>
2.设置配置文件
文件名为: hibernate.cfg.xml
<?xml version=‘1.0‘ encoding=‘utf-8‘?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- 数据库连接 --> <property name="hibernate.connection.driver_class">oracle.jdbc.OracleDriver</property> <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:XE</property> <property name="hibernate.connection.username">SC1901</property> <property name="hibernate.connection.password">ROOT</property> <!-- 数据库方案 --> <property name="hibernate.default_schema">SC1901</property> <!-- 数据库方言 --> <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property> <!-- 调试相关配置 --> <property name="hibernate.format_sql">true</property> <property name="hibernate.show_sql">true</property> <!-- 自动建表方式 通过实体类来生成表--> <!--create:表示启动的时候先drop,再create--> <!--create-drop: 也表示创建,只不过再系统关闭前执行一下drop--> <!--update: 这个操作启动的时候会去检查schema是否一致,如果不一致会做scheme更新--> <!--validate: 启动时验证现有schema与你配置的hibernate是否一致,如果不一致就抛出异常,并不做更新--> <property name="hibernate.hbm2ddl.auto">update</property> <!--实体类--> <mapping class="com.seecen.model.User"/> <mapping class="com.seecen.model.Role"/> </session-factory> </hibernate-configuration>
通过实体类来创建一张表
package com.seecen.model; import javax.persistence.*; /** * Author: TaoTao 2019/6/24 */ @Table(name = "t_ssh_user") //实体类对应的表 @Entity //持久层对应的实体类 public class User { private Integer userId; private String userName; private String userPwd; private Integer roleId; private String remark; private String temp; @Id//主键 @Column(name = "user_id") //字段名 //定义一个系列 @SequenceGenerator(name = "gen",sequenceName = "seq_t_ssh_user", allocationSize = 1) //自增策略 @GeneratedValue(generator = "gen",strategy = GenerationType.SEQUENCE) public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } @Column(name = "user_name",length = 200) public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } @Column(name = "user_psw") public String getUserPwd() { return userPwd; } public void setUserPwd(String userPwd) { this.userPwd = userPwd; } @Column(name = "role_id") public Integer getRoleId() { return roleId; } public void setRoleId(Integer roleId) { this.roleId = roleId; } @Column(name = "remark") public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } //失效字段 @Transient public String getTemp() { return temp; } public void setTemp(String temp) { this.temp = temp; } }
@Table(name = "t_ssh_user") 实体类对应的表
@Entity //持久层的实体类
@Id//主键
@Column(name = "user_id") 列相关属性
@Transient 失效字段
//定义一个序列
@SequenceGenerator(name = "gen", sequenceName = "seq_t_ssh_user", allocationSize = 1)
//自增策略
@GeneratedValue(generator = "gen", strategy = GenerationType.SEQUENCE)
创建表
import org.hibernate.boot.Metadata; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.boot.spi.MetadataImplementor; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.junit.Test; /** * Author: TaoTao 2019/6/24 */ public class CreateTable { @Test public void create(){ //读取配置文件 StandardServiceRegistryBuilder builder= new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml"); //解析配置文件,生成媒体数据 Metadata metadata = new MetadataSources(builder.build()).buildMetadata(); //根据媒体数据创建或更新表结构 new SchemaExport((MetadataImplementor) metadata).create(true,true); } @Test public void createRole(){ //读取配置文件 StandardServiceRegistryBuilder builder= new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml"); //解析配置文件,生成媒体数据 Metadata metadata = new MetadataSources(builder.build()).buildMetadata(); //根据媒体数据创建或更新表结构 new SchemaExport((MetadataImplementor) metadata).create(true,true); } }
持久化操作
import com.seecen.model.User; import org.hibernate.*; import org.hibernate.cfg.Configuration; import org.hibernate.criterion.Projection; import org.hibernate.criterion.ProjectionList; import org.hibernate.criterion.Projections; import org.hibernate.criterion.Restrictions; import org.junit.Assert; import org.junit.Test; import java.util.List; /** * Author: TaoTao 2019/6/24 */ public class UserDao extends BaseDao { @Test public void add(){ //读取配置文件 Configuration cfg = new Configuration().configure("hibernate.cfg.xml"); //创建sessiono工厂 SessionFactory factory = cfg.buildSessionFactory(); //打开session Session session = factory.openSession(); //开始事务 Transaction transaction = session.beginTransaction(); //持久化操作 User user = new User(); user.setUserName("黄蓉"); user.setUserPwd("123"); user.setRoleId(1); //Session对象中封装了一列的增删改查方法 session.save(user); transaction.commit(); session.close(); } @Test public void update(){ User user = new User(); user.setUserName("李四"); user.setUserId(1); session.update(user); } @Test public void get(){ //第一个参数:查询那张表,第二个参数:主键 User user = session.get(User.class, 1); Assert.assertNotNull(user); } @Test public void del(){ //根据主键删除 User user = new User(); user.setUserId(1); session.delete(user); } @Test public void updateSelective(){ Integer id = 2; String userName= "曹操"; User user = session.get(User.class,2); user.setUserName("靖哥哥"); session.update(user); } @Test public void saveOrUpdate(){ User user = new User(); user.setUserId(2); user.setUserName("周伯通"); session.saveOrUpdate(user); //有就更新,没就插入 } // 带条件 @Test public void findByCondition(){ // 面向对象的方式来完成数据库的条件查询 //创建条件兑现 Criteria cri = session.createCriteria(User.class); //组装查询条件 // cri.add(Restrictions.eq("userName","黄蓉")); // cri.add(Restrictions.eq("userId",4)); cri.add(Restrictions.or( Restrictions.eq("userName","黄蓉"), Restrictions.isNotNull("userName"))); List<User> list = cri.list(); Assert.assertTrue(list.size()>0); } @Test public void findByPage(){ Criteria cri = session.createCriteria(User.class); // 设置开始位置【从0开始】 // 设置查询数量 cri.setFirstResult(1).setMaxResults(2); List<User> list = cri.list(); Assert.assertTrue(list.size()>0); } //聚合函数的使用 @Test public void count(){ Criteria cri = session.createCriteria(User.class); //把聚合函数的信息装进Criteria对象中 cri.setProjection(Projections.rowCount()); Long totalCount = (Long) cri.uniqueResult(); Assert.assertTrue(totalCount>0); } // 同时执行多个聚合函数 @Test public void multiFun(){ Criteria cri = session.createCriteria(User.class); ProjectionList proList = Projections.projectionList(); proList.add(Projections.rowCount()).add(Projections.max("userId")); cri.setProjection(proList); //根据查询信息(查询那张表,条件,聚合函数)生成sql语句 Object[]result = (Object[]) cri.uniqueResult();//查询结果集为一条记录的时候调用unique System.out.println(result[0]); System.out.println(result[1]); Assert.assertTrue(result.length==2); } // 分组查询 @Test public void groupby(){ // select count(*),role_id from t_user group by role_id; Criteria cri = session.createCriteria(User.class); ProjectionList proList = Projections.projectionList(); proList.add(Projections.rowCount()).add(Projections.groupProperty("roleId"));//根据角色id分组(属性) cri.setProjection(proList); // Object[] result = (Object[]) cri.uniqueResult(); //返回一条记录用uniqueResult()方法; List list = cri.list(); //返回的是多条记录用户list()方法 Assert.assertTrue(list.size()>0); } @Test public void entityState(){ User user = new User(); //临时状态,修改对象属性不会影响到数据库 user.setUserName("小黄"); session.save(user); //持久状态 //调用save方法之后,实体类user会变成持久状态 transaction.commit(); //创建新事物 Transaction transaction = session.beginTransaction(); user.setUserName("老王"); //没有调用update,但user对象是持久状态,修改持久状态的属性值,会影响到数据库 transaction.commit(); session.close();//suer对象就变成游离状态,修改属性不会影响数据库 } @Test public void hql(){ Query query = session.createQuery("from User"); List<User> list = query.list(); Assert.assertTrue(list.size()>0); } @Test public void hqlByCondition(){ Query query = session.createQuery("from User where userName like ? and roleId = ? or userPwd = ?"); query.setString(0,"%黄%"); query.setInteger(1,4); query.setString(2,"123"); //分页 query.setFirstResult(0).setMaxResults(2); List<User> list = query.list(); Assert.assertTrue(list.size()>0); } }
继承的父类
import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.junit.After; import org.junit.Before; /** * Author: TaoTao 2019/6/24 */ public class BaseDao { protected Session session; protected Transaction transaction; @Before public void start(){ Configuration configuration = new Configuration().configure(); SessionFactory factory = configuration.buildSessionFactory(); session = factory.openSession(); transaction = session.beginTransaction(); } @After public void end(){ transaction.commit(); session.close(); } }
原文:https://www.cnblogs.com/book-mountain/p/11079199.html