码迷,mamicode.com
首页 > Web开发 > 详细

【Hibernate一】概述及入门

时间:2015-07-16 20:02:00      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:框架   hibernate   

Hibernate学习框架:
1、基本部分
     crud的操作
     主键的生成机制
     类型
     持久化类
     映射文件 *.hbm.xml
     配置文件 hibernate.cfg.xml
2、关系部分
     一对多的单项
     一对多的双向
     多对多的双向
     一对一
        在many-to-one加一个属性unique="true"
        cascade  级联
        inverse  维护关系  <set>中lazy,fetch
3、性能的部分
  • 维护关系 inverse
  • 懒加载 lazy
  • 抓取策略 fetch
  • 一级缓存 
  • 二级缓存
查询缓存
4、查询
    hql
    条件查询


一。Hibernate概述:
在servlet中,操作数据库我们使用的是jdbc,为了更加方便的操作数据库,我们可以使用ORM框架,ORM:Object Relation Mapping,对象关系映射,目的就是像操作java普通的类一样来操作数据库。显然Hibernate是ORM框架中做得比较好的一款!

Hibernate的有点:
  • 面向对象数据库编程;
  • 代码书写更加简洁;
  • 具有缓存机制,提高效率;

二.入门:
准备条件:
1.导入相关的包
技术分享
2.hibernate.cfg.xml:(通常位于scr根目录下)
数据库要自己先新建好!!
<?xml version= ‘1.0‘ encoding =‘utf-8‘?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd" >

<hibernate-configuration>
     <session-factory >
           <!-- 数据库的用户名 -->
           <property name="connection.username" >root </property>
           <!-- 密码 -->
           <property name="connection.password" >root </property>
           <!-- url -->
           <property name= "connection.url">
              jdbc:mysql:// localhost:3306/hibernate512
           </property>
           <!-- 方言 告诉hibernate,要操作的数据库是mysql -->
           <property name="dialect" >org.hibernate.dialect.MySQLDialect </property>
           <!-- 导入驱动 -->
           <property name= "connection.driver_class" >
              com.mysql.jdbc.Driver
           </property>
     
           <!-- validate 只检查结构 update 检查结构,更新或者创建表 create 每次启动 hibernate时,都要创建表 create-drop
              启动 hibernate时创建表,当 hibernate关闭时,删除表 -->
           <property name= "hbm2ddl.auto">update</property >
           <!--显示sql语句的输出  -->
           <property name= "show_sql"> true</ property >
            <property name= "format_sql"> true</ property >
          
           <!--关联映射文件,手动添加,然后自动生成!  -->
           <mapping resource="com/oteman/hibernate/domain/Person.hbm.xml" />
     
     </session-factory >

</hibernate-configuration>

3.要操作的实体bean(Person为例)
package com.oteman.hibernate.domain;

public class Person {
     Long pid;
     String pname;
     String pgender;
     public Long getPid() {
           return pid ;
     }
     public void setPid(Long pid) {
           this.pid = pid;
     }
     public String getPname() {
           return pname ;
     }
     public void setPname(String pname) {
           this.pname = pname;
     }
     public String getPgender() {
           return pgender ;
     }
     public void setPgender(String pgender) {
           this.pgender = pgender;
     }

}


4.要操作的实体与数据库表的对应关系Person.hbm.xml
(通常与实体bean在同一个目录)
<?xml version= "1.0" encoding ="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >

<!-- 数据库表和类之间的映射关系  字段和表列名之间的关系 -->
<hibernate-mapping>
     <class name="com.oteman.hibernate.domain.Person"  table="Person" >
           <id name= "pid" column ="pid" length="5" type="java.lang.Long" >
               <generator class= "increment"></generator >
           </id>
           <property name= "pgender" column ="gender" length="10" type="string"></ property>
           <property name= "pname" column ="name" length="20" ></property>
     </class >

</hibernate-mapping>


5.根据配置文件建立表
     @Test
     public void testCreateTable(){
          Configuration configuration= new Configuration();
          configuration.configure();
          SessionFactory sessionFactory = configuration.buildSessionFactory();
     }


6.增删改查:
/**
      * 向数据库中增加数据
      */
     @Test
     public void add(){

          Session session = sessionFactory.openSession();
          Transaction transaction = session.beginTransaction();
          Person p= new Person();
          p.setPgender( "男");
          p.setPname( "张三");
          session.save(p);
          transaction.commit();
          session.close();
     }
     
     /**
      * 更新数据, hibernate具有快照机制,会将对象前后的值进行比较,如果发现对象的属性没有发生改变,那么就不进行update操作,可以观察 sql语句;
      */
     @Test
     public void update(){
          Session session = sessionFactory.openSession();
          Transaction transaction = session.beginTransaction();
          Person person=(Person) session.get(Person. class, 2l);
          person.setPname( "哈哈");
           /*//第二种形式:
          Person p=new Person();
          p.setPgender("男");
          p.setPid(2L);
          p.setPname("李四");*/
          session.update(person);
          transaction.commit();
          session.close();
     }
     /**
      * 删除数据
      */
     @Test
     public void delete(){
          Session session= sessionFactory.openSession();
          Transaction transaction = session.beginTransaction();
          Person person=(Person) session.get(Person. class, 1l);
          session.delete(person);
          
          transaction.commit();
          session.close();
          
     }
     /**
      * 查询所有!
      */
     @Test
     public void query(){
          Session session= sessionFactory.openSession();
           List list = session.createQuery("from Person").list();
          System. out.println(list.size());
          session.close();
     }

7.Generator主键产生机制
public class GeneratroTest extends HibernateUtils{
     
     /**
      *
      * 1.<id name=" pid" column="pid" type="java.lang.Long">
               <generator class="increment"> </generator>
           </id>
      * increament形式产生的 sql语句
      *    Hibernate:
              select
                  max( pid)
              from
                  person
           Hibernate:
              insert
              into
                  person
                  ( pname, psex , pid)
              values
                  (?, ?, ?)
                 
           说明:
              1、先得到主键的最大值
              2、在最大值的基础上加1
              3、上述的两步过程是由 hibernate内部完成的
      */
     @Test
     public void testIncrement(){
          Session session =  sessionFactory.openSession();
          Transaction transaction = session.beginTransaction();
          Person person = new Person();
           //person.setPid(11L);为increament时,自行设置的id没有用, hibernate会帮我们处理id;
          person.setPname( "云三班长" );
          person.setPsex( "不详");
          session.save(person);
          transaction.commit();
          session.close();
     }
     
     /**
      *
      * 2.<generator class="identity"> </generator>
      *
      * Hibernate:
         insert
         into
             person
             ( pname, psex )
         values
             (?, ?)
             说明:
               主键的生成交给数据库来做,数据库必须支持自动增长机制,会出现id不连续的情况,效率比increment要高一些;
      */
     @Test
     public void testIdentity(){
          Session session =  sessionFactory.openSession();
          Transaction transaction = session.beginTransaction();
          Person person = new Person();
           //person.setPid(11L);
          person.setPname( "云三班长" );
          person.setPsex( "不详");
          session.save(person);
          transaction.commit();
          session.close();
     }
     
     /**
      * 3.<generator class=" uuid"></generator>
      * 主键的生成是由 hibernate内部完成的
      */
     @Test
     public void testUUID(){
          Session session =  sessionFactory.openSession();
          Transaction transaction = session.beginTransaction();
          Person person = new Person();
          person.setPname( "云三班长" );
          person.setPsex( "不详");
          session.save(person);
          transaction.commit();
          session.close();
     }
     /**
      * 4.<generator class="assign"> </generator>
      * 主键的生成由自己指定。
      */
     @Test
     public void testAssigned(){
          Session session =  sessionFactory.openSession();
          Transaction transaction = session.beginTransaction();
          Person person = new Person();
          person.setPid(11L);
          person.setPname( "云三班长" );
          person.setPsex( "不详");
          session.save(person);
          transaction.commit();
          session.close();
     }
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

【Hibernate一】概述及入门

标签:框架   hibernate   

原文地址:http://blog.csdn.net/damogu_arthur/article/details/46914109

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!