1、什么是orm
ORM(Object Relational Mapping)或O/RM,或O/R Mapping,称为:对象关系映射。
ORM是通过使用描述对象和数据库之间映射的元数据,将Java中的对象自动持久化到关系数据库中。
本质上就是将数据从一种形式转换到另外一种形式。
1.1. 为什么要使用ORM?
面向对象的开发方法是当今企业级应用开发环境中的主流开发方法,关系数据库是企业级应用环境中永久存放数据的主流数据存储系统。
传统JDBC开发的问题:
开发烦琐,重复劳动。
非常了解操作数据库底层的API。
1. Hibernate简介
Hibernate是一个开源的ORM框架,它对JDBC进行了非常轻量级的对象封装,它将POJO与数据库表建立映射关系,是一个全自动的ORM框架。
注:Hibernate可以自动生成SQL语句、自动执行,使得Java程序员可以随心所欲的使用对象编程思维来操纵数据库(不建议自动生成)。
Hibernate可以应用在任何使用JDBC的场合,既可以在Java的客户端程序使用,也可以在Servlet/JSP的Web应用中使用,最具革命意义的是,Hibernate可以在应用EJB的J2EE架构中取代CMP,完成数据持久化的重任。
1.1. JDBC与Hibernate的比较
JDBC的速度最快,因为它是直连数据库。
而Hibernate是DAO层的框架,专门连接数据库,简化封装了JDBC,同时也牺牲一部分性能,所以Hibernate比JDBC慢很多。
l JDBC速度快,操作麻烦;
l Hibernate速度慢,操作简单;
l ibaites界于这两者之间。
如何添加相关的依赖
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>com.lww</groupId> 5 <artifactId>T224_hibernate</artifactId> 6 <packaging>war</packaging> 7 <version>0.0.1-SNAPSHOT</version> 8 <name>T224_hibernate Maven Webapp</name> 9 <url>http://maven.apache.org</url> 10 <properties> 11 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 12 <maven.compiler.source>1.8</maven.compiler.source> 13 <maven.compiler.target>1.8</maven.compiler.target> 14 <junit.version>4.12</junit.version> 15 <servlet.version>4.0.0</servlet.version> 16 <hibernate.version>5.3.0.Final</hibernate.version> 17 <mysql.driver.version>5.1.46</mysql.driver.version> 18 </properties> 19 <dependencies> 20 <dependency> 21 <groupId>junit</groupId> 22 <artifactId>junit</artifactId> 23 <version>${junit.version}</version> 24 <scope>test</scope> 25 </dependency> 26 27 <dependency> 28 <groupId>javax.servlet</groupId> 29 <artifactId>javax.servlet-api</artifactId> 30 <version>${servlet.version}</version> 31 <scope>provided</scope> 32 </dependency> 33 34 <dependency> 35 <groupId>org.hibernate</groupId> 36 <artifactId>hibernate-core</artifactId> 37 <version>${hibernate.version}</version> 38 </dependency> 39 40 <dependency> 41 <groupId>mysql</groupId> 42 <artifactId>mysql-connector-java</artifactId> 43 <version>${mysql.driver.version}</version> 44 </dependency> 45 </dependencies> 46 <build> 47 <finalName>T224_hibernate</finalName> 48 <plugins> 49 <plugin> 50 <groupId>org.apache.maven.plugins</groupId> 51 <artifactId>maven-compiler-plugin</artifactId> 52 <version>3.7.0</version> 53 <configuration> 54 <source>${maven.compiler.source}</source> 55 <target>${maven.compiler.target}</target> 56 <encoding>${project.build.sourceEncoding}</encoding> 57 </configuration> 58 </plugin> 59 </plugins> 60 </build> 61 </project>
2.在resource目录下添加hibernate.cfg.xml(核心配置文件)
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE hibernate-configuration PUBLIC 3 "-//Hibernate/Hibernate Configuration DTD 3.0//EN" 4 "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> 5 6 <hibernate-configuration> 7 <session-factory> 8 <!-- 1. 数据库相关 --> 9 <property name="connection.username">root</property> 10 <property name="connection.password">123</property> 11 <property name="connection.url">jdbc:mysql://localhost:3306/t224?useUnicode=true&characterEncoding=UTF-8 12 </property> 13 <property name="connection.driver_class">com.mysql.jdbc.Driver</property> 14 <property name="dialect">org.hibernate.dialect.MySQLDialect</property> 15 16 <!-- 配置本地事务(No CurrentSessionContext configured!) --> 17 <property name="hibernate.current_session_context_class">thread</property> 18 19 <!-- 2. 调试相关 --> 20 <property name="show_sql">true</property> 21 <property name="format_sql">true</property> 22 23 <!-- 3. 添加实体映射文件 --> 24 <mapping resource="com/liuwenwu/one/entity/User.hbm.xml" /> 25 26 </session-factory> 27 </hibernate-configuration>
3.建立实体类User
1 package com.liuwenwu.one.entity; 2 import java.sql.Date; 3 import java.sql.Timestamp; 4 public class User { 5 private Integer id; 6 private String userName; 7 private String userPwd; 8 private String sex; 9 private Date birthday; 10 private String realName; 11 private Timestamp createDatetime; 12 private String remark; 13 public Integer getId() { 14 return id; 15 } 16 public void setId(Integer id) { 17 this.id = id; 18 } 19 public String getUserName() { 20 return userName; 21 } 22 public void setUserName(String userName) { 23 this.userName = userName; 24 } 25 public String getUserPwd() { 26 return userPwd; 27 } 28 public void setUserPwd(String userPwd) { 29 this.userPwd = userPwd; 30 } 31 public String getSex() { 32 return sex; 33 } 34 public void setSex(String sex) { 35 this.sex = sex; 36 } 37 public Date getBirthday() { 38 return birthday; 39 } 40 public void setBirthday(Date birthday) { 41 this.birthday = birthday; 42 } 43 public String getRealName() { 44 return realName; 45 } 46 public void setRealName(String realName) { 47 this.realName = realName; 48 } 49 public Timestamp getCreateDatetime() { 50 return createDatetime; 51 } 52 public void setCreateDatetime(Timestamp createDatetime) { 53 this.createDatetime = createDatetime; 54 } 55 public String getRemark() { 56 return remark; 57 } 58 public void setRemark(String remark) { 59 this.remark = remark; 60 } 61 62 public User() { 63 super(); 64 } 65 public User(Integer id, String userName, String userPwd, String sex, Date birthday, String realName, 66 Timestamp createDatetime, String remark) { 67 super(); 68 this.id = id; 69 this.userName = userName; 70 this.userPwd = userPwd; 71 this.sex = sex; 72 this.birthday = birthday; 73 this.realName = realName; 74 this.createDatetime = createDatetime; 75 this.remark = remark; 76 } 77 @Override 78 public String toString() { 79 return "User [id=" + id + ", userName=" + userName + ", userPwd=" + userPwd + ", sex=" + sex + ", birthday=" 80 + birthday + ", realName=" + realName + ", createDatetime=" + createDatetime + ", remark=" + remark 81 + "]"; 82 } 83 }
4.实体类的配置文件 User.hbm.xml 映射实体类(User)
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE hibernate-mapping PUBLIC 3 "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 4 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 5 <hibernate-mapping> 6 <!-- 7 class标签: 8 name:对应的是需要映射的实体类的全路径名 9 table:实体类对应的数据库中的表名 10 11 id标签: 配置的是表中的主键 12 name:对应的是实体类属性名 13 type:指的是实体类数据类型 14 column:数据库表对应的列名 15 16 property标签:配置除主键以为列段对应的类属性映射关系 17 name:对应的是实体类属性名 18 type:指的是实体类数据类型 19 column:数据库表对应的列名 20 insert="false" update="false" 表示该列段或者说该属性只做查询使用,不做更新(修改) 21 22 --> 23 <class name="com.liuwenwu.one.entity.User" table="t_hibernate_user"> 24 <id name="id" type="java.lang.Integer" column="id"> 25 <generator class="increment" /> 26 </id> 27 <property name="userName" type="java.lang.String" column="user_name"> 28 </property> 29 <property name="userPwd" type="java.lang.String" column="user_pwd"> 30 </property> 31 <property name="realName" type="java.lang.String" column="real_name"> 32 </property> 33 <property name="sex" type="java.lang.String" column="sex"> 34 </property> 35 <property name="birthday" type="java.sql.Date" column="birthday"> 36 </property> 37 <property insert="false" update="false" name="createDatetime" 38 type="java.sql.Timestamp" column="create_datetime"> 39 </property> 40 <property name="remark" type="java.lang.String" column="remark"> 41 </property> 42 </class> 43 </hibernate-mapping>
接下来是CRUD的演示
查询:
1 package com.liuwenwu.demo; 2 import java.util.List; 3 import org.hibernate.Session; 4 import org.hibernate.SessionFactory; 5 import org.hibernate.cfg.Configuration; 6 7 /** 8 * hibernate查询演示 9 * @author ASUS 10 */ 11 public class QueryDemo { 12 public static void main(String[] args) { 13 Configuration configure = new Configuration().configure("/hibernate.cfg.xml"); 14 SessionFactory sessionFactory = configure.buildSessionFactory(); 15 //会话 而这里的会话指的是操作数据库的链接 16 Session session = sessionFactory.openSession(); 17 List list = session.createQuery("from User").list(); 18 for (Object obj : list) { 19 System.out.println(obj); 20 } 21 session.close(); 22 } 23 }
新增:
1 package com.liuwenwu.demo; 2 import java.sql.Date; 3 import java.sql.Timestamp; 4 import java.util.List; 5 import org.hibernate.Session; 6 import org.hibernate.SessionFactory; 7 import org.hibernate.Transaction; 8 import org.hibernate.cfg.Configuration; 9 10 import com.liuwenwu.one.entity.User; 11 12 /** 13 * hibernate新增演示 14 * @author ASUS 15 * 16 */ 17 public class InsertDemo { 18 public static void main(String[] args) { 19 Configuration configure = new Configuration().configure("/hibernate.cfg.xml"); 20 SessionFactory sessionFactory = configure.buildSessionFactory(); 21 //会话 而这里的会话指的是操作数据库的链接 22 Session session = sessionFactory.openSession(); 23 Transaction transaction = session.beginTransaction(); 24 session.save(new User(null, "aa", "版本", "男", new Date(System.currentTimeMillis()), "存储", new Timestamp(System.currentTimeMillis()), "信息")); 25 26 transaction.commit(); 27 session.close(); 28 } 29 30 }
修改:
1 package com.liuwenwu.demo; 2 3 import java.sql.Date; 4 import java.sql.Timestamp; 5 import org.hibernate.Session; 6 import org.hibernate.SessionFactory; 7 import org.hibernate.Transaction; 8 import org.hibernate.cfg.Configuration; 9 import com.liuwenwu.one.entity.User; 10 11 /** 12 * hibernate修改演示 13 * @author ASUS 14 * 15 */ 16 public class UpdateDemo { 17 public static void main(String[] args) { 18 Configuration configure = new Configuration().configure("/hibernate.cfg.xml"); 19 SessionFactory sessionFactory = configure.buildSessionFactory(); 20 //会话 而这里的会话指的是操作数据库的链接 21 Session session = sessionFactory.openSession(); 22 Transaction transaction = session.beginTransaction(); 23 // session.save(new User(null, "aa", "版本", "男", new Date(System.currentTimeMillis()), "存储", new Timestamp(System.currentTimeMillis()), "信息")); 24 // User u=new User(null, "aa", "版本", "男", new Date(System.currentTimeMillis()), "存储", new Timestamp(System.currentTimeMillis()), "信息"); 25 // u.setRealName("啥"); 26 User user = session.get(User.class, 2); 27 user.setRealName("三毛"); 28 transaction.commit(); 29 session.close(); 30 } 31 }
删除:
1 package com.liuwenwu.demo; 2 import org.hibernate.Session; 3 import org.hibernate.SessionFactory; 4 import org.hibernate.Transaction; 5 import org.hibernate.cfg.Configuration; 6 import com.liuwenwu.one.entity.User; 7 8 /** 9 * hibernate删除的演示 10 * @author ASUS 11 * 12 */ 13 public class DeleteDemo { 14 public static void main(String[] args) { 15 Configuration configure = new Configuration().configure("/hibernate.cfg.xml"); 16 SessionFactory sessionFactory = configure.buildSessionFactory(); 17 //会话 而这里的会话指的是操作数据库的链接 18 Session session = sessionFactory.openSession(); 19 Transaction transaction = session.beginTransaction(); 20 User user = new User(); 21 user.setId(2); 22 session.delete(user); 23 transaction.commit(); 24 session.close(); 25 } 26 }
Hibernate的管理对象的三种状态运行图解