Hibernate概念:
Hibernate是链接Java应用程序和关系型数据库的框架,能够建立对象模型于关系型数据模型之间的映射,是一种自动ORM框架。Hibernate位于分层体系结构中的持久层,是完成对象持久化的框架。Hibernate是对JDBC API的封装,是JDBC轻量级封装框架。Hibernate特点:
Hibernate实现了ORM,使Java程序员可以方便的运用面向对象的编程思想来操作数据库。Hibernate是对JDBC的封装,增强了代码的重用性,简化了代码,提高了编程效率。Hibernate是对JDBC的轻量级封装,必要时Java程序员可以绕过Hibernate直接访问JDBC API。Hibernate不仅可以应用于独立的Java程序中,还可以应用在Java Web项目中,并支持多种数据库平台。Hibernate框架搭建的流程:
1、安装Eclipce、Mysql; //Mysql个人建议安装mysql-8.0.11-winx64 或者 ;
2、下载Hibernate,并解压缩; // 进入Hibernate官网:http://hibernate.org/orm/ ;下载hibernate-release-5.2.10.Final
3、使用Eclipse创建新项目; //创建一个普通的Java项目即可
4、引入Hibernate并在项目的lib文件中引入依赖库(jar包);
5、在lib目录下引入Mysql数据库驱动包; //mysql-connector-java-8.0.15.jar
6、编写Hibernate配置文件; //
//hibernate.cfg.xml配置文件代码如下 <?xml version="1.0" encoding="UTF-8"?> <!--表明解析本XML文件的DTD文档位置,DTD是Document Type Definition 的缩写,即文档类型的定义, XML解析器使用DTD文档来检查XML文件的合法性。hibernate.sourceforge.net/hibernate-configuration-3.0dtd可以在Hibernate3.1.3软件包中的src\org\hibernate目录中找到此文件--> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <!--Hibernate配置文件的根元素,其他文件要包含在其中--> <hibernate-configuration> <!--SessionFactory是Hibernate中的一个类,这个类主要负责保存Hibernate的配置信息,以及对session的操作--> <session-factory> <!--hibernate.dialect 只是Hibernate使用的数据库方言,就是要用Hibernate连接那种类型的数据库服务器。--> <property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property> <!--配置数据库的驱动程序,Hibernate在连接数据库时,需要用到数据库的驱动程序--> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <!--设置数据库的连接url:jdbc:mysql://localhost:3306/dbname,其中localhost表示mysql服务器名称,此处为本机, dbname是数据库名--> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/orm?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC</property> <!-- 连接数据库时数据的传输字符集编码方式 --> <property name="hibernate.connection.characterEncoding">UTF-8</property> <!--连接数据库时的用户名--> <property name="hibernate.connection.username">root</property> <!--连接数据库时的密码--> <property name="hibernate.connection.password">hgb123</property> <!--是否在后台显示Hibernate用到的SQL语句,开发时设置为true,便于差错, 程序运行时可以在Eclipse的控制台显示Hibernate的执行Sql语句。项目部署后可以设置为false,提高运行效率--> <property name="hibernate.show_sql">true</property> <!-- 格式化输出的Sql语句 --> <property name="hibernate.format_sql">true</property> <property name="hibernate.hbm2ddl.auto">update</property> <!--指定映射文件,可映射多个映射文件--> <!-- <mapping class="com.wpf.entity.Department"/> <mapping class="com.wpf.entity.Employee"/> --> <mapping resource="com/wpf/entity/Department.hbm.xml"/> <mapping resource="com/wpf/entity/Employee.hbm.xml"/> </session-factory> </hibernate-configuration>
7、创建Java持久化类XXX.java; //(Java Bean类)
以我上面项目hibernateotdd为例,创建两个持久化类Department.java与Employee.java
//持久化类Department.java,代码如下 import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; import org.hibernate.annotations.Cascade; @Entity @Table(name="department") public class Department { private Integer id; private String name; private Set<Employee> employees=new HashSet<Employee>(); public Department(){ } public Department(Integer id, String name) { this.id = id; this.name = name; } @Id @GeneratedValue(strategy=GenerationType.IDENTITY) public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } @Column(name="name") public String getName() { return name; } public void setName(String name) { this.name = name; } @OneToMany(targetEntity=Employee.class,mappedBy="department",cascade=CascadeType.ALL) public Set<Employee> getEmployees() { return employees; } public void setEmployees(Set<Employee> employees) { this.employees = employees; } @Override public String toString() { return "Department [id=" + id + ", name=" + name + "]"; } }//持久化类Employee.java,代码如下 import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.Fetch; import org.hibernate.annotations.Proxy; //@Proxy(lazy=false) @Entity @Table(name="employee") public class Employee { private Integer id; private String name; private String telephone; private Department department; public Employee(){ } public Employee(String name, String telephone) { super(); this.name = name; this.telephone = telephone; } @Id @GeneratedValue(strategy=GenerationType.IDENTITY) public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } @Column(name="name") public String getName() { return name; } public void setName(String name) { this.name = name; } @Column(name="telephone") public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } @ManyToOne @JoinColumn(name="did") public Department getDepartment() { return department; } public void setDepartment(Department department) { this.department = department; } @Override public String toString() { return "Employee [id=" + id + ", name=" + name + ", telephone=" + telephone + "]"; } }
8、编写Java持久化类的映射配置文件XXX.hbm.xml;
创建两个持久化类Department.java与Employee.java对应映射配置文件
//Department.hbm.xml代码如下 <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.wpf.entity"> <!-- name属性设定类名(包含路径); table属性设定表名,默认以类名作表名。--> <class name="Department" table="department" > <id name="id" column="id" > <generator class="identity"> </generator> </id> <property name="name" column="name" > <!-- <column name="" sql-type=""></column> --> </property> <!-- <set name="employees" inverse="true" lazy="true" outer-join="true" fetch="subselect"> <key column="did"></key> <one-to-many class="Employee"/> </set> --> <!-- 设置级联;Testjb中,不用执行session.save(employee1);语句 --> <!-- cascade属性代表设置级联 --> <!-- 当cascade为all时,为设置级联,则Testjb中 --> <!-- inverse属性代表改变外键的级联维护,设置谁来维护外键; (默认)false:不放弃维护,由自己(部门)维护外键 true:放弃维护,由多方(员工)来维护外键 --> <!-- 当inverse为false时,Testjd中 --> <set name="employees" cascade="all" > <key column="did"></key> <one-to-many class="Employee"/> </set> </class> </hibernate-mapping> //Employee.hbm.xml代码如下 <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.wpf.entity"> <class name="Employee" table="employee" > <id name="id" column="id" > <generator class="identity"> </generator> </id> <property name="name" column="name" /> <property name="telephone" column="telephone"></property> <!-- name是在员工里面创建一个属性department; --> <!-- many-to-one只提供cascade属性,不提供inverse属性,默认值为false --> <many-to-one name="department" column="did" class="Department" outer-join="false" fetch="join"></many-to-one> </class> </hibernate-mapping>
9、使用Hibernate API 完成对象的持久化;
//test测试代码如下 import java.util.List; import java.util.Set; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.hibernate.query.Query; import com.wpf.entity.Department; import com.wpf.entity.Employee; import com.wpf.util.HibernateUtil; public class Testjb { /** * 12.19 测试类--->使用基本对象查询 */ public static void main(String[] args) { save(); // delete(); // find(); // findZq(); } public static void findZq() { Session session = null; Transaction tran = null; try { session = HibernateUtil.openSession(); tran = session.beginTransaction(); // --------------------------------- // 查询部门对象 // Query query=session.createQuery("from Department"); // List<Department> list = query.list(); // for (Department department : list) { // System.out.println(department.getEmployees().size()); // } Query query=session.createQuery("from Employee"); List<Employee> list = query.list(); for (Employee e : list) { System.out.println(e.getDepartment().getName()); } tran.commit(); } catch (Exception e) { e.printStackTrace(); tran.rollback(); } finally { if (null != session) { session.close(); } } } public static void find() { Session session = null; Transaction tran = null; try { session = HibernateUtil.openSession(); tran = session.beginTransaction(); // --------------------------------- // 查询部门对象 // Department department=session.load(Department.class, 4); // Set<Employee> employees = department.getEmployees(); // for (Employee employee : employees) { // System.out.println(employee.getName()); // // } // System.out.println(department.getId()); //查询员工对象 Employee employee=session.load(Employee.class, 6); System.out.println(employee.getName()); System.out.println(employee.getDepartment().getName()); // --------------------------------- tran.commit(); } catch (Exception e) { e.printStackTrace(); tran.rollback(); } finally { if (null != session) { session.close(); } } } /* * * 实现添加部门功能 */ public static void save() { Configuration cfg=new Configuration().configure(); SessionFactory factory=cfg.buildSessionFactory(); Session session=factory.openSession(); Transaction tran=session.beginTransaction(); Department department=new Department(); department.setName("执行部"); Employee employee1=new Employee(); employee1.setName("董事"); employee1.setTelephone("564"); // employee1.setDepartment(department); //将员工设置成什么部门,告诉员工是哪个部门 Employee employee2=new Employee(); employee2.setName("中心"); employee2.setTelephone("785"); //不执行employee2.setDepartment(department);时,did为NULL,因为外键did需要更新 // employee2.setDepartment(department); //将员工设置成什么部门,告诉员工是哪个部门,建立员工到部门的关联关系 department.getEmployees().add(employee1); //告诉部门,有哪个员工,由部门到员工的关联关系 department.getEmployees().add(employee2); //告诉部门,有哪个员工,维护级联,还要进行update语句,更新外键did,比较影响性能,改为由多方(员工)来维护外键did // session.save(employee1); //当Department.hbm.xml文件中设置了级联cascade,这不用执行这个语句。<set name="employees" cascade="all" > // session.save(employee2); session.save(department); //当Department.hbm.xml文件中设置了级联cascade为all时,只需要执行这条语句添加部门属性,也会自动添加员工属性,提高代码效率(不用执行多条session.save(employee2);语句) System.out.println("department"+department); tran.commit(); session.close(); factory.close(); } /* * * 实现部门删除功能 */ public static void delete() { Session session = null; Transaction tran = null; try { session = HibernateUtil.openSession(); tran = session.beginTransaction(); // --------------------------------- // 查找Department对象 Department department = session.load(Department.class, 8); System.out.println(department.getName()); session.delete(department); // --------------------------------- tran.commit(); } catch (Exception e) { e.printStackTrace(); tran.rollback(); } finally { if (null != session) { session.close(); } } } }