您的位置:首页 > 编程语言 > Java开发

JavaEE-Hibernate

2015-11-13 10:29 579 查看
Hibernate
sf2gis@163.com
2015年10月9日
 

1  目标:实现对象和关系的映射。

ORM框架(object relationmapping),关系表和对象模式映射,通过对象操作关系表。

2 原理:将表映射为一个类,列映射为类的属性,行映射为对象。PO=pojo+映射文件。实现JPA规范。

Hibernate是一个开放源代码的对象关系映射框架,它对JDBC进行了非常轻量级的对象封装,可以使用面向象编程思维来操纵数据库。

参考:

http://baike.baidu.com/link?url=LN0NmAxi6sIfeJNpkSKstnEPz2q1E8XNxLGbstyDSRP0Sd-gWonssQeeYeMIn6XdqISLuhNA3EzLr413Y0enzK

3 流程:安装hibernate,配置database,创建实体类,配置映射文件,操作实体类。

参考:http://blog.csdn.net/oscar999/article/details/27237027

http://blog.csdn.net/doodoofish/article/details/43207/

3.1 安装Hibernate:下载,安装lib,配置buildpath。

3.1.1下载:从官网下载需要的hiberante(本文档使用3.6)。

3.1.2安装hibernate tools插件:在eliclipse中安装hibernate tools

参见:JavaIDE-Eclipse.docxeclipse market部分。

3.1.3安装lib:在eclipse中新建一个java application,并创建lib文件夹,将lib中的部分jar复制到lib中。

使用required、jap、bytecode中全部jar。

3.1.4配置buildpath:在buildpath中添加lib中的所有jar。

3.2 配置database:本文使用mysql。

3.2.1安装mysql:参见:..\DataBase\mysql\mysql.docx

创建数据库:create database hib4;

创建表:create table employee。

create table employee(idint(11) not null auto_increment, emp_name varchar(100) default null, emp_adressvarchar(500) default null, emp_mobile_nos varchar(100) default null, primarykey (id));

3.2.2安装jdbc驱动:下载jdb驱动,安装到lib和buildpath

3.2.2.1  下载jdbc驱动:本文使用mysql。

下载后解压,使用其中的mysql-connector-java-5.1.36-bin.jar。

附:常用驱动下载地址

Oracle JDBC Driver下载地址(下载前必须同意Oracle协议书)
http://otn.oracle.com/software/htdocs/distlic.html?/software/tech/java/sqlj_jdbc/htdocs/jdbc9201.html

MySQL JDBC Driver下载地址
http://dev.mysql.com/downloads/connector/j/3.0.html

PostgreSQL JDBC Driver下载地址
http://jdbc.postgresql.org/download.html

MS-SQL Server JDBC Driver下载地址
http://www.microsoft.com/downloads/details.aspx?FamilyID=9f1874b6-f8e1-4bd6-947c-0fc5bf05bf71&displaylang=en

3.2.2.2  安装到lib文件夹中:将jar复制到lib文件夹。

3.2.2.3  配置到buildpath:将jar添加到buildpath

3.3 创建实体类:关系表的映射实体类

一般采用表名为类名,列名为属性名,使用Bean规范设置Getter/Setter。

参考:http://www.roseindia.net

示例:employee实体类。

package lee;

 

import java.io.Serializable;

 

public class Employee implements Serializable{

 

      private int id; 

      private String empName;

      private String empAddress;   

      private String empMobileNos;

 

      public int getId() {

           return id;

      }

 

      public void setId(int id) {

           this.id = id;

      }

 

      public String getEmpName() {

           return empName;

      }

 

      public voidsetEmpName(String empName) {

           this.empName = empName;

      }

 

      public StringgetEmpAddress() {

           return empAddress;

      }

 

      public voidsetEmpAddress(String empAddress) {

           this.empAddress =empAddress;

      }

 

      public String getEmpMobileNos(){

           return empMobileNos;

      }

 

      public voidsetEmpMobileNos(String empMobileNos) {

           this.empMobileNos =empMobileNos;

      }

}

3.4 配置映射表:Hibernate数据库配置和实体映射配置

3.4.1hibernate数据库配置:全局配置。

参考:

http://stackoverflow.com/questions/16400761/org-hibernate-exception-sqlgrammarexception-could-not-insert-hibernate-with-my

3.4.1.1  使用数据源测试数据库配置:更新mysql的jdbc驱动,设置相应的url和用户名密码。测试成功后,可以在DataSource栏看到相应的表。

3.4.1.2  创建全局配置文件:hibernate.cfg.xml

new->hibernate configure file创建全局配置文件,配置完成后生成xml文件。

注意:为了看到每次操作实体时生成的sql语句,设置show_sql属性:

<property name="show_sql">true</property> 

示例: hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-configuration PUBLIC

           "-//Hibernate/HibernateConfiguration DTD 3.0//EN"

           "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>

       <propertyname="show_sql">true</property>

       <propertyname="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

        <propertyname="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>

        <propertyname="hibernate.connection.password">sf</property>

        <propertyname="hibernate.connection.url">jdbc:mysql://localhost:3306/hib4</property>

        <propertyname="hibernate.connection.username">root</property>

        <mapping resource="Employee.hbm.xml"/>

    </session-factory>

</hibernate-configuration>

3.4.2实体映射配置:ClassName.hbm.xml

3.4.2.1  new->hibernate xml mapping file创建实体关系映射文件,配置完成后生成xml文件。

注意:默认hibernate生成的映射文件中,关系相关的关键字是大写的,但是MySQL在Linux下默认对表名是大小写敏感的。需要修改一个MySQL的规则(参见:..\DataBase\mysql\mysql.docx
配置部分),可以修改表名为小写。

注意:查看自动生成的表名、列名与实际的表名、列名是否相同,如果不同需要手动修改。

 

3.4.2.2  生成的xml文件要放到全局配置文件中。

        <mappingresource="Employee.hbm.xml"/>

示例:Employee.hbm.xml

<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/HibernateMapping DTD 3.0//EN"

                                  "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<!-- Generated Oct 10, 2015 4:25:37 PM by Hibernate Tools 3.4.0.CR1-->

<hibernate-mapping>

 <classname="lee.Employee" table="EMPLOYEE">

  <id name="id"type="int">

   <columnname="ID"/>

   <generatorclass="assigned"/>

  </id>

  <propertygenerated="never" lazy="false" name="empName"type="java.lang.String">

   <columnname="EMP_NAME"/>

  </property>

  <propertygenerated="never" lazy="false" name="empAddress"type="java.lang.String">

   <columnname="EMP_ADDRESS"/>

  </property>

  <propertygenerated="never" lazy="false"name="empMobileNos" type="java.lang.String">

   <column name="EMP_MOBILE_NOS"/>

  </property>

 </class>

</hibernate-mapping>

3.5 操作实体类:  使用Hibernate操作数据库

参考:http://blog.csdn.net/rcfalcon/article/details/5684546

示例:Main.java

package lee;

 

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.Transaction;

import org.hibernate.cfg.Configuration;

 

public class Main {

 

      public static voidmain(String[] args) {

           // TODO Auto-generatedmethod stub

           Configuration cfg = newConfiguration().configure();

           SessionFactory sf =cfg.buildSessionFactory();

           Session session =sf.openSession();

 

           // read

           {

                 Employee obj = (Employee) session.load(Employee.class, 1);

                 System.out.println(obj.getEmpName()+":"+obj.getEmpMobileNos());

           }

           // delete

           {

                 Employee obj =(Employee) session.load(Employee.class, 4);

                 session.delete(obj);

                 System.out.println("delete="+obj.getEmpName());

           }

           // update

           {

                 Employee obj =(Employee) session.load(Employee.class, 7);

                 obj.setEmpName("updatexxx");

                 System.out.println(obj.getEmpName()+":"+obj.getEmpMobileNos());

           }

           // insert

           {

                 Transaction trans= session.beginTransaction();

                 Employee n = newEmployee();

                 n.setEmpAddress("xxx");

                 n.setEmpMobileNos("yyy");

                 n.setEmpName("zzz");

                 session.save(n);

                 trans.commit();

           }

           session.close();

           sf.close();

      }

}

结果:

Hibernate: select employee0_.ID as ID0_0_, employee0_.EMP_NAME asEMP2_0_0_, employee0_.EMP_ADDRESS as EMP3_0_0_, employee0_.EMP_MOBILE_NOS as EMP4_0_0_from EMPLOYEE employee0_ where employee0_.ID=?

zzz:yyy

Hibernate: select employee0_.ID as ID0_0_, employee0_.EMP_NAME asEMP2_0_0_, employee0_.EMP_ADDRESS as EMP3_0_0_, employee0_.EMP_MOBILE_NOS asEMP4_0_0_ from EMPLOYEE employee0_ where employee0_.ID=?

delete=zzz

Hibernate: select employee0_.ID as ID0_0_, employee0_.EMP_NAME asEMP2_0_0_, employee0_.EMP_ADDRESS as EMP3_0_0_, employee0_.EMP_MOBILE_NOS asEMP4_0_0_ from EMPLOYEE employee0_ where employee0_.ID=?

updatexxx:yyy

Hibernate: insert into EMPLOYEE (EMP_NAME, EMP_ADDRESS, EMP_MOBILE_NOS,ID) values (?, ?, ?, ?)

Hibernate: delete from EMPLOYEE where ID=?

4 方法:Hibernate(RedHat旗下)。

参考:http://www.cnblogs.com/whjblogs/p/3137385.html

4.1 组织结构:数据库操作对象

数据库上下文:SessionFactory,控制与数据库相关参数,操作连接对象。

连接:Session,数据库连接,操作事务对象等。

事务:Transaction。

持久化对象:PO,与Session建立连接的POJO。

4.2 操作流程:加载配置文件,创建数据库操作对象。

参考:http://blog.csdn.net/alex_zhuang/article/details/6724910

http://www.cnblogs.com/shanmu/p/3598477.html

4.2.1加载全局配置文件:Configuration。

用于加载全局配置文件,默认使用configure()加载hibernate.cfg.xml。

也可以指定自定义的配置文件。

      Configuration cfg = newConfiguration().configure();

4.2.2创建数据库上下文:SessionFactory。

使用Configuration创建数据库上下文,buildSessionFactory。

SessionFactory sf = cfg.buildSessionFactory();

4.2.3创建连接:Session。

使用SessionFactory的openSession()创建一个连接。

Session session = sf.openSession();

4.2.4操作数据数据库:事务和PO。

通过Transaction创建事务。

Transaction trans = session.beginTransaction();

通过Session创建PO。

Employee obj = (Employee) session.load(Employee.class, 4);

4.3 配置文件:数据库配置、表配置

4.3.1数据库映射:根据数据库连接参数,配置hibernate.cfg.xml。

默认名称为hiberante.cfg.xml。一般采用默认名称。Hiberante的Configuration().configure()将会默认加载此文档。

|根元素为<hibernate-configuration>

|-连接工厂:<session-factory>,session代表一个连接。将由此处产生一个连接。

|--连接参数:<prpoperty name=”参数key”>value</property>

|--PO映射文件列表:<mappingresource=”xml”/>,每个xml代表一个PO映射。

示例:

<?xml version="1.0"encoding="GBK"?>

<!DOCTYPEhibernate-configuration PUBLIC

           "-//Hibernate/Hibernate Configuration DTD3.0//EN"

           "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>

        <propertyname="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>

        <propertyname="hibernate.connection.password">test</property>

        <propertyname="hibernate.connection.url">jdbc:mysql://localhost:3306/testdb</property>

        <propertyname="hibernate.connection.username">test</property>

        <propertyname="hibernate.connection.password">test</property>

        <propertyname="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>

        <property name="hibernate.hbm2ddl.auto">update</property>      

        <mappingresource="News.hbm.xml"/>

    </session-factory>

</hibernate-configuration>

4.3.2表映射:将po和数据库表的映射,文件名为class.hbm.xml。

|根元素:<hibernate-mapping>

|-PO类:<class name=”po类”table=”数据库表”>

|--PO类主属性:<id name=”主键属性名” type=”属性类型,可选”>

|---数据库表列:<column name=”列名”/>

|---主键生成方式:identity(数据库自动增长),assigned(外部赋值)等多种方式。

|--PO类其它属性:<propertyname=”属性名”>

|---数据库表列:<column name=”列名“/>

参考:http://jingyemingyue.iteye.com/blog/1686741

示例:

<?xmlversion="1.0"?>

<!DOCTYPEhibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<!-- Generated 2015-6-722:11:18 by Hibernate Tools 3.4.0.CR1 -->

<hibernate-mapping>

    <class name="News"table="news_table">

        <id name="id"type="java.lang.Integer">

            <column name="id"/>

            <generatorclass="identity" />

        </id>

        <property name="title" type="java.lang.String">

            <column name="title"/>

        </property>

        <property name="content"type="java.lang.String">

            <column name="content"/>

        </property>

    </class>

</hibernate-mapping>

4.4 自动生成:数据库生成持久类(po,persistent object)和po生成数据库

4.4.1 po生成数据库:操作po类,将由session入库。

4.4.1.1  加载数据库映射文件:Configuration().configure()。

4.4.1.2  连接数据库:SessionFactory生成Session。

4.4.1.3  事件开启:Transaction。

4.4.1.4  操作PO。

4.4.1.5  入库(持久化):Session.save(po对象)。提交事务。

4.4.1.6  清理:关闭连接和连接工厂。

示例:

      public static void main(String[] args) {

           // TODO Auto-generated method stub

           Configuration cfg = new Configuration().configure();

           SessionFactory sf = cfg.buildSessionFactory();

           Session session = sf.openSession();

           Transaction trans = session.beginTransaction();

           News n = new News();

           n.setId(11);

           n.setTitle("test hib");

           n.setContent("test hib content");

           session.save(n);

           trans.commit();

           session.close();

           sf.close();

      }

4.4.2数据库生成类:Hibernate Code Generation,生成需要的类。

参见:http://www.cnblogs.com/yjmyzz/archive/2012/12/26/2834037.html

4.4.2.1  配置数据库和Hibernate:参见准备:配置数据库和Hibernate

4.4.2.2  连接数据库:在Hibernate Configuration中配置,并连接至数据库。

4.4.2.3  配置需要生成PO的表:在Hibernate Code Gen中配置反向参数。

4.4.2.4  生成PO:Run生成PO类。需要将使用的PO文件copy到工程目录。

4.4.2.5  配置PO:将生成的PO类xml文件,配置到cfg.xml中。

4.4.2.6  使用PO:参见po生成数据库:操作po类,将由session入库。

示例:

      public static void main(String[] args) {

           // TODO Auto-generated method stub

           Configuration cfg = new Configuration().configure();

           SessionFactory sf = cfg.buildSessionFactory();

           Session session = sf.openSession();

           Transaction trans = session.beginTransaction();

           operateGen(session);

           trans.commit();

           session.close();

           sf.close();

      }

     

      public static void operateGen(Session session)

      {

           StuBasicInfo stu = (StuBasicInfo)session.load(StuBasicInfo.class, new String("A0111"));

           System.out.println(stu.getStuId()+"="+stu.getStuName()+","+stu.getGendar());

           stu.setStuName("test1");

           stu.setGendar("女");

           System.out.println(stu.getStuId()+"="+stu.getStuName()+","+stu.getGendar());

      }  

4.5 互操作:数据库->po,po->数据库

4.5.1从数据库读取PO:从数据库中生成PO类:load(可延迟加载)或get(直接加载)。

4.5.2从PO写入数据库:save(obj[,key])或persist(obj[,key]),或将load/get加载的类直接修改。

4.5.3将脱管的PO重新写入数据库:update()、merge()、updateOrSave()。

update():已经持久化过的对象入库。

save():瞬间对象持久化并入库。

merge():瞬间对象的数据入库,本身仍然是瞬间对象。

4.5.4使用PO删除数据库数据:delete()。

session.delete(obj);

4.5.5PO状态:瞬间对象(内存对象,未入库),持久对象(库中的对象,已经连接),游离对象(库中的对象,但连接已经关闭)。

4.6 连接池:C3P0

默认的连接池由于性能问题不推荐使用,推荐使用C3P0连接池。

默认连接池配置:设置pool_size。

<property name="hibernate.connection.pool_size">10</property>

C3P0配置:设置连接池的大小等属性。

  <propertyname="hibernate.c3p0.max_size">10</property>

  <propertyname="hibernate.c3p0.min_size">3</property>

  <propertyname="hibernate.c3p0.timeout">1800</property>

  <propertyname="hibernate.c3p0.max_statements">50</property>

参考:http://www.cnblogs.com/JemBai/archive/2009/10/26/1589755.html

4.7 数据库方言:SQL的具体实现标准

由于不同的数据对SQL有不同的实现,方言就是指定具体的实现。

      <propertyname="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

4.8 使用容器的数据源(不推荐):JDNI连接容器的数据源。

可以设置JDNI连接容器的数据源,但是由于需要与容器耦合,不推荐使用。

4.9 缓存设置:cache,提高性能

4.10 注释Annotation:使用JPA的注释功能代替XML格式的实体映射配置文件。

Annotation包括Hibernate和JPA两种,JPA是标准格式,推荐使用(可以切换为其它的ORM)。

参考:http://www.cnblogs.com/hongten/archive/2011/07/20/2111773.html

http://blog.csdn.net/fancylovejava/article/details/7438660

http://www.cnblogs.com/seed_lee/archive/2011/02/14/1954720.html

4.10.1流程:在全局配置文件中设置映射的实体类,然后在实体类中设置注释

4.10.1.1 在全局配置文件中设置映射的实体类

  <mappingclass="lee.Employee"/>

4.10.1.2 在实体类中为不同的角色设置各种不同的注释

package lee;

 

import java.io.Serializable;

 

importjavax.persistence.Column;

importjavax.persistence.Entity;

importjavax.persistence.GeneratedValue;

importjavax.persistence.GenerationType;

import javax.persistence.Id;

import javax.persistence.Table;

 

@Entity

@Table(name="employee")

public class Employeeimplements Serializable{

      @Id

      @Column(name="id")

      @GeneratedValue(generator="gen",strategy=GenerationType.AUTO)

      private int id; 

      @Column(name="emp_name")

      private String empName;

      @Column(name="emp_address")

      private String empAddress;

      @Column(name="emp_mobile_nos")

      private String empMobileNos;

 

      public int getId() {

           return id;

      }

 

      public void setId(int id) {

           this.id = id;

      }

 

      public String getEmpName() {

           return empName;

      }

 

      public void setEmpName(String empName) {

           this.empName = empName;

      }

 

      public String getEmpAddress() {

           return empAddress;

      }

 

      public void setEmpAddress(String empAddress) {

           this.empAddress = empAddress;

      }

 

      public String getEmpMobileNos() {

           return empMobileNos;

      }

 

      public void setEmpMobileNos(String empMobileNos) {

           this.empMobileNos = empMobileNos;

      }

}

4.10.2方法:实体映射配置文件的注释格式

4.10.2.1 实体类映射:@Entity,@Table

@Entity将此类标识为一个实体类。

@Table指定此类对应的表名。

4.10.2.2 主键映射:@Id,@GeneratedValue(generator="gen",strategy=GenerationType.AUTO)

@Id将此属性标识为主键。

@GeneratedValue指定主键的生成策略。

@Column指定id对应的列名。

4.10.2.3 列映射:@Column(name="column_name")

@Column指定属性对应的列名。

4.10.3方法:直接使用SQL语句

使用Session的createSQLQuery(sql语句)创建查询,然后使用executeUpdate()。

参考:http://blog.csdn.net/xumengxing/article/details/8728255

           Session ss=getSessionFactory().openSession();

           SQLQuery query = ss.createSQLQuery("delete fromlemployee where id=19");   

   intresult = query.executeUpdate();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  JavaEE Java SSH Hibernate