Hibernate学习笔记(一)

####1.1Hibernate框架的学习路线
第一天:Hibernate的入门(Hibernate的环境搭建、Hibernate的API、Hibernate的CRUD)
第二天:Hibernate的一级缓存、其他的API
第三天:Hibernate的一对多配置、Hibernate的多对多的配置
第四天:Hibernate的查询方式、抓取策略

####1.2CRM的案例

1.2.1CRM的概述(了解)
1.2.1.1什么是CRM 客户关系管理
1.2.1.2CRM有哪些模块

#####1.3Hibernate的框架的概述
1.3.1.1什么是框架
框架:指的是软件的半成品,已经完成了部分功能。
1.3.2EE的三层架构
1.3.2.1EE的经典三层结构

ORM:对象关系映射,指的是将一个java中的对象与关系型数据库中的表建立一种映射关系,从而操作对象就可以完成数据库的相关操作

###实例如下:

    首先先看下数据库的创造

CREATE TABLE `cst_customer` (
  `cust_id` bigint(32) NOT NULL AUTO_INCREMENT COMMENT '客户编号(主键)',
  `cust_name` varchar(32) NOT NULL COMMENT '客户名称(公司名称)',
  `cust_source` varchar(32) DEFAULT NULL COMMENT '客户信息来源',
  `cust_industry` varchar(32) DEFAULT NULL COMMENT '客户所属行业',
  `cust_level` varchar(32) DEFAULT NULL COMMENT '客户级别',
  `cust_phone` varchar(64) DEFAULT NULL COMMENT '固定电话',
  `cust_mobile` varchar(16) DEFAULT NULL COMMENT '移动电话',
  PRIMARY KEY (`cust_id`)'主键'
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

这样就创建了一个数据表

然后就是根据这个数据表创建一个对应的类

public class HibernateDemo1 {
    
    private long cust_id;
    private String cust_name;
    private String cust_source;
    private String cust_industry;
    private String cust_level;
    private String cust_phone;
    private String cust_mobile;
    public long getCust_id() {
        return cust_id;
    }
    public void setCust_id(long cust_id) {
        this.cust_id = cust_id;
    }
    public String getCust_name() {
        return cust_name;
    }
    public void setCust_name(String cust_name) {
        this.cust_name = cust_name;
    }
    public String getCust_source() {
        return cust_source;
    }
    public void setCust_source(String cust_source) {
        this.cust_source = cust_source;
    }
    public String getCust_industry() {
        return cust_industry;
    }
    public void setCust_industry(String cust_industry) {
        this.cust_industry = cust_industry;
    }
    public String getCust_level() {
        return cust_level;
    }
    public void setCust_level(String cust_level) {
        this.cust_level = cust_level;
    }
    public String getCust_phone() {
        return cust_phone;
    }
    public void setCust_phone(String cust_phone) {
        this.cust_phone = cust_phone;
    }
    public String getCust_mobile() {
        return cust_mobile;
    }
    public void setCust_mobile(String cust_mobile) {
        this.cust_mobile = cust_mobile;
    }
    
}

下面就是配置类和数据表之间的关联。命名的规则是xxx.hbm.xml文件。习惯上采用类的名字作为命名

          首先需要做的是配置映射的关系,映射关系的文件放置在类文件的同级根目录下

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<!--以上部分是固定的格式可以在我们的Hibernate的导包中找到-->
   
<!--下面就是开始创建对应的映射关系-->
 <hibernate-mapping>
 <!-- 建立类与表的映射 -->
    <class name="com.hibernate.learn.HibernateDemo1" table="cst_customer">
           <!--  建立类中的属性与表中的主键对应-->
           <id name="cust_id" column="cust_id">
               <generator class="native"></generator>
           </id>
           <!-- 建立类中的普通的属性和表中字段的对应。除了主键用id其他都用property -->
           <property name="cust_name" column="cust_name"></property>
           <property name="cust_source" column="cust_source"></property>
           <property name="cust_industry" column="cust_industry"></property>
           <property name="cust_level" column="cust_level"></property>
           <property name="cust_phone" column="cust_phone"></property>
           <property name="cust_mobile" column="cust_mobile"></property>
    </class>
 </hibernate-mapping>

至此映射关系配置完毕

下面需要做的是数据库连接的配置文件,这个文件的命名格式是Hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<!--同样的上面这块属于固定的文件配置,下面的就是Hibernate的相关配置-->    
<hibernate-configuration>
    <session-factory>
    <!-- 连接数据库的基本配置。这块属于数据库的固定配置模式,这里的数据库是mysql数据库-->
         <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
         <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
         <property name="hibernate.connection.username">root</property>
         <property name="hibernate.connection.password">root</property>
         <!-- 配置Hibernate的方言。意思是指你采用的是什么数据库,因为mysql,orcle等很多数据库的要求是不一样的。所以要在此处进行配置 -->
         <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
         
         <!-- 打印sql语句到控制台,不是必须要有的配置-->
         <property name="hibernate.show_sql">true</property>
         
          <!-- 自动建表的配置 -->
         <property name="hibernate.hbm2ddl.auto">update</property>
         
         
         <!-- 配置C3P0连接池 .如果需要使用c3p0可以通过这种方式来完成导入-->
        <property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
        <!--在连接池中可用的数据库连接的最少数目 -->
        <property name="c3p0.min_size">5</property>
        <!--在连接池中所有数据库连接的最大数目  -->
        <property name="c3p0.max_size">20</property>
        <!--设定数据库连接的过期时间,以秒为单位,
        如果连接池中的某个数据库连接处于空闲状态的时间超过了timeout时间,就会从连接池中清除 -->
        <property name="c3p0.timeout">120</property>
         <!--每3000秒检查所有连接池中的空闲连接 以秒为单位-->
        <property name="c3p0.idle_test_period">3000</property>
         
         
         <!-- 格式化sql,是控制台输出的数据库语句更加美观,不是必须要有的配置 -->
         <property name="hibernate.format_sql">true</property>
         
         <!--最终映射到刚刚的类与数据表映射的配置文件xxx.hbm.xml-->
         <mapping resource="com/hibernate/learn/Hibernate.hbm.xml"></mapping>
    </session-factory>
</hibernate-configuration>

至此Hibernate的相关配置完成

最后开始对数据库经行操作

public static void main(String[] args) throws SecurityException, HeuristicMixedException, HeuristicRollbackException, RollbackException, SystemException {
        //保存客户的案例
        //1.加载Hibernate核心配置文件
        Configuration configuration=new Configuration().configure();
        
        //2.创建一个SessionFactory对象:类似于JDBC中连接池
        SessionFactory sessionFactory=configuration.buildSessionFactory();
        
        //3.通过SessionFactory获取到Session对象,类似于JDBC中的Connection
        Session session=sessionFactory.openSession();
        
        //4.手动开启事务:
        Transaction transaction=(Transaction) session.beginTransaction();
        
        //5.编写代码
        HibernateDemo1 hibernateDemo1=new HibernateDemo1();
        
        hibernateDemo1.setCust_name("zyz");
        session.save(hibernateDemo1);
        
        //6.事务提交
        transaction.commit();
        
        //7.释放资源
        session.close();
    }

OK至此相关的简单的案例完成

 

#####1.5Hibernate的相关配置

###【class标签的配置】
标签用来建立类与表的映射关系
属性:
 name :类的全路径
 table :表名(类名与表名一致,table可以省略)
 catalog :数据库名

###【id标签的配置】
标签用来建立类中的属性与表中的主键的对应关系
 属性:
 name :类中的属性名
 column :表中的字段名(类中的属性名和表中的字段名如果一致,column可以省略)
 length :长度
 type :类型


###【property标签的配置】
标签用来建立类中的普通属性与表的字段的对应关系
属性:
name :类中的属性名
column :表中的字段名
length :长度
type :类型
not-null :设置非空
unique :设置唯一

#######核心配置
#######必须的配置
 连接数据库的基本的参数
 驱动类
 url路径
 用户名
 密码
 方言


####可选的配置
 显示SQL :hibernate.show_sql
 格式化SQL :hibernate.format_sql


#####自动建表 :hibernate.hbm2ddl.auto

none :不使用hibernate的自动建表
create :如果数据库中已经有表,删除原有表,重新创建,如果没有表,新建表。(测试)
create-drop :如果数据库中已经有表,删除原有表,执行操作,删除这个表。如果没有表,新建一个,使用完了删除该表。(测试)
update :如果数据库中有表,使用原有表,如果没有表,创建新表(更新表结构)
validate :如果没有表,不会创建表。只会使用数据库中原有的表。(校验映射和表结构)。
映射文件的引入
引入映射文件的位置 <mapping resource="com/hibernate/learn/Hibernate.hbm.xml"></mapping>

#######1.6Hibernate的核心API

####作用:
###加载核心配置文件
 hibernate.properties
Configuration cfg = new Configuration();


hibernate.cfg.xml
Configuration cfg = new Configuration().configure();


加载映射文件
// 手动加载映射
configuration.addResource("com/itheima/hibernate/demo1/Customer.hbm.xml");

##########SessionFactory:Session工厂
SessionFactory内部维护了Hibernate的连接池和Hibernate的二级缓存(不讲)。是线程安全的对象。一个项目创建一个对象即可。

<!-- 配置C3P0连接池 -->
<property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
<!--在连接池中可用的数据库连接的最少数目 -->
<property name="c3p0.min_size">5</property>
<!--在连接池中所有数据库连接的最大数目 -->
<property name="c3p0.max_size">20</property>
<!--设定数据库连接的过期时间,以秒为单位,
如果连接池中的某个数据库连接处于空闲状态的时间超过了timeout时间,就会从连接池中清除 -->
<property name="c3p0.timeout">120</property>
<!--每3000秒检查所有连接池中的空闲连接 以秒为单位-->
<property name="c3p0.idle_test_period">3000</property>

#############Session:类似Connection对象是连接对象

#####Session代表的是Hibernate与数据库的链接对象。不是线程安全的。与数据库交互桥梁。
 #####Session中的API
 保存方法:
 Serializable save(Object obj);

public void test(){
         Session session=HibernateUtils.GetSession();
           //手动开启事务
           Transaction transaction=session.beginTransaction();
           
           HibernateDemo1 hibernateDemo1=new HibernateDemo1();
           hibernateDemo1.setCust_name("宋培闯");
            session.save(hibernateDemo1);
           transaction.commit();//事件的提交
           session.close();//会话关闭
    }


 查询方法:
 T get(Class c,Serializable id);
 T load(Class c,Serializable id);


 get方法和load方法的区别?

//使用get的方法进行查询
    public void TestDemo2(){
         Session session=HibernateUtils.GetSession();
         //手动开启事务
          Transaction transaction=session.beginTransaction();
          //使用get方式查询
          HibernateDemo1 hibernateDemo1=new HibernateDemo1();
          hibernateDemo1=session.get(HibernateDemo1.class,1l);
          System.out.println(hibernateDemo1.toString());
          transaction.commit();//事件的提交
          session.close();//会话关闭
    }
    
    //使用load方式查询
    public void TestLoad(){
        Session session=HibernateUtils.GetSession();
           //手动开启事务
        Transaction transaction=session.beginTransaction();
        HibernateDemo1 hibernateDemo1=new HibernateDemo1();
        hibernateDemo1=session.load(HibernateDemo1.class,2l);
        System.out.println(hibernateDemo1.toString());
        transaction.commit();//事件的提交
        session.close();//会话关闭
    }

区别

 修改方法
 void update(Object obj);

//修改的方法
    public void updateTest(){
         Session session=HibernateUtils.GetSession();
         //手动开启事务
         Transaction transaction=session.beginTransaction();
         //直接创建对象,进行修改:不推荐使用,因为会导致为设置的值全部变为空
        /* HibernateDemo1 hibernateDemo1=new HibernateDemo1();
         hibernateDemo1.setCust_id(1l);
         hibernateDemo1.setCust_name("修改名字");
         session.update(hibernateDemo1);*/
         //先查询在修改
         HibernateDemo1 hibernateDemo1=new HibernateDemo1();
         hibernateDemo1=session.get(HibernateDemo1.class,1l);
         hibernateDemo1.setCust_name("修改名字");
         session.update(hibernateDemo1);
         transaction.commit();//事件的提交
         session.close();//会话关闭
    }


 删除方法
 void delete(Object obj);

//删除的方法
    public void DeleteTest(){
        Session session=HibernateUtils.GetSession();
         //手动开启事务
         Transaction transaction=session.beginTransaction();
         //直接创建对象删除
         /*HibernateDemo1 hibernateDemo1=new HibernateDemo1();
         hibernateDemo1.setCust_id(1l);
         session.delete(hibernateDemo1);*/
         //先查询再删除,推荐使用这一种方式
         HibernateDemo1 hibernateDemo1=new HibernateDemo1();
         hibernateDemo1=session.get(HibernateDemo1.class,1l);
         session.delete(hibernateDemo1);
         transaction.commit();//事件的提交
         session.close();//会话关闭
    }
    
    

保存或更新
 void saveOrUpdate(Object obj)

//保存或更新的方法(不常用)
    public void TestDemo1(){
        Session session=HibernateUtils.GetSession();
        //手动开启事务
        Transaction transaction=session.beginTransaction();
        
        //如果数据库中没有这条数据就是添加,如果有这条数据,那就是修改
        HibernateDemo1 hibernateDemo1=new HibernateDemo1();
        hibernateDemo1.setCust_name("testets");
        session.saveOrUpdate(hibernateDemo1);
        transaction.commit();//事件的提交
        session.close();//会话关闭
    }
//查询所有的信息
    public void TestDemo03(){
        Session session=HibernateUtils.GetSession();
        //手动开启事务
        Transaction transaction=session.beginTransaction();
        //接收HQL:hibernate Query Language 面向对象的查询语句
        /*org.hibernate.Query query=session.createQuery("from HibernateDemo1");
        List<HibernateDemo1> list=query.list();
        for(HibernateDemo1 hibernateDemo1:list){
            System.out.println(hibernateDemo1.toString());
        }*/
        //接收SQL
        SQLQuery query=session.createSQLQuery("select *from cst_customer");
        List <Object[]> list=query.list();
        for(Object[] objects:list){
            System.out.println(Arrays.toString(objects));
        }
        transaction.commit();//事件的提交
        session.close();//会话关闭
    }

 其中HibernateUtils代码如下

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtils {
    //这个包的主要重用是为了放置工具类
    //这个工具类是Hibernate的工具类
    
    public static final Configuration cfg;
    public static final SessionFactory sf;//创建一个SessionFactory对象:类似于JDBC中连接池
    
    static{
        //加载Hibernate核心配置文件
        cfg=new Configuration().configure();
        sf=cfg.buildSessionFactory();//此处相当于创建工厂
    }
    //对外设置一个接口
    public static Session GetSession(){
        //通过SessionFactory获取到Session对象,类似于JDBC中的Connection
        return sf.openSession();
    }
}

猜你喜欢

转载自www.cnblogs.com/byczyz/p/11415881.html
今日推荐