hibernate入门---uuid.hex生成方式【依据机器标识等自生】【第二天】

在进行这个实例之前,先说之前出现的问题:

1、类前面一定要避免有空格,在这之前,从未想过类名前面有空格还能创建文件;在配置的时候,会出现如果没有空格,就无法找到映射类。当然,加了空格就可以,但请避免使用。

2、在配置过程中,请一定要根据需要创建数据库表,并且这个表的主键是否考虑整型,默认值,是否自增等。

3、运行过程中报错,优先看控制台,判断出错问题,快速定位;如无法找到,再运用其他技巧。

下面:先将之前几个实例用到的数据库表及本次使用的表贴出来:

表1:

CREATE TABLE `customers` (
  `customerID` varchar(8) NOT NULL,
  `name` varchar(15) DEFAULT NULL,
  `phone` varchar(16) DEFAULT NULL,
  PRIMARY KEY (`customerID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

表2:

CREATE TABLE `customers2` (
  `customerID` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(15) DEFAULT NULL,
  `phone` varchar(16) DEFAULT NULL,
  PRIMARY KEY (`customerID`)
) ENGINE=InnoDB AUTO_INCREMENT=1015 DEFAULT CHARSET=utf8;

 

表3:

CREATE TABLE `customers3` (
  `customerID` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(15) DEFAULT NULL,
  `phone` varchar(16) DEFAULT NULL,
  PRIMARY KEY (`customerID`)
) ENGINE=InnoDB AUTO_INCREMENT=1015 DEFAULT CHARSET=utf8;

 

表4:(略,Oracle数据库测试)

表5:

CREATE TABLE `customers5` (
  `customerID` varchar(50) NOT NULL,
  `name` varchar(15) DEFAULT NULL,
  `phone` varchar(16) DEFAULT NULL,
  PRIMARY KEY (`customerID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

表5示例 uuid.hex生成方式【依据机器标识等自生】

一、Customer.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-mapping package="bean" auto-import="false">
   <!-- POJO类映射表及某表的关系-->
   <class name="bean.Customer5" table="customers5" catalog="test">
       <id name="customerID" type="java.lang.String">
           <column name="customerID"/>
           <generator class="uuid.hex"></generator>
       </id>
       <!-- 映射表中name字段 -->
       <property name="name" type="java.lang.String">
          <column name="name" length="40"/>
       </property>
       <!-- 映射表中phone字段 -->
       <property name="phone" type="java.lang.String">
          <column name="phone" length="16"/>
       </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-configuration>
<!-- 配置文件标签顺序property*,mapping*,(class-cache|collection-cache),event,listener* -->
    <session-factory>
      <!-- 设置访问mysql数据库的驱动描述 -->
      <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
      <!-- 设置数据库的url -->
      <property name="connection.url">jdbc:mysql://127.0.0.1:3306/test</property>
      <!-- 指定登录数据库用户账户 -->
      <property name="connection.username">root</property>
      <!-- 指定登录数据库用户密码 -->
      <property name="connection.password">123456</property>
      
      <!-- 设置访问数据库的方言,提高数据库访问性能 -->
      <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
      <!-- 设置ddl -->
      <!-- <property name="hbm2ddl.auto">auto</property> -->
       <!-- 配置控制台视图,显示查询内容 -->
       <property name="show_sql">true</property>
       <!-- 下面是多表映射 -->
      <!-- 指出映射文件 -->
      <mapping resource="resource/Customer.hbm.xml"/>
      <!-- 映射文件 -->
      <mapping resource="resource/Customer2.hbm.xml"/>
      <!-- 映射文件 -->
      <mapping resource="resource/Customer3.hbm.xml"/>
      <!-- 映射文件 -->
      <mapping resource="resource/Customer5.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

三、Customer5.java

package bean;

//验证uuid.hex生成主键方式的映射类,数据库对应表customers2
public class Customer5 {
    private String customerID;
    private String name,phone;
    
    public String  getCustomerID() {
        return customerID;
    }

    public void setCustomerID(String  customerID) {
        this.customerID = customerID;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }
}

四、HibernateSessionFactory.java

package hibernate.factory;


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


public class HibernateSessionFactory {
    private static String configfile = "resource/hibernate.cfg.xml";
    /**ThreadLocal是一个本地线程**/
    private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private static Configuration config;
    private static SessionFactory sessionFactory;
    /**读取配置文件,创建一个工厂会话,这段代码为静态块,编译后已经运行**/
    static{
        try {
            config = new Configuration().configure(configfile);
            sessionFactory = config.buildSessionFactory();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }
    /**通过会话工厂打开会话,就可以访问数据库了**/
    public static Session getSession(){
        Session session = (Session)threadLocal.get();
        if (session==null||!session.isOpen()) {
            if (sessionFactory==null) {
                rebuildSessionFactory();
            }
            session = (sessionFactory!=null)?sessionFactory.openSession():null;
        }
        return session;
    }
    /**重新创建一个会话工厂**/
    public static void rebuildSessionFactory() {
        try {
            config.configure(configfile);
            sessionFactory = config.buildSessionFactory();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }
    /**关闭与数据库的会话**/
    public static void closeSession() {
        Session session = (Session)threadLocal.get();
        threadLocal.set(null);
        if (session!=null) {
            session.close();
        }
    }
}

五、Customer5Demo.java

package bean;

import java.util.List;




import hibernate.factory.HibernateSessionFactory;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;


//用于测试increment主键生成方式,增加记录,不建议使用,他是实例自增,多实例访问时,会重复主键,出问题
//由于是增加数据,所以不需要写Query,只需要new表,增加数据即可
public class Customer5Demo {
    Session session = HibernateSessionFactory.getSession();
    Transaction tran = session.beginTransaction();
    public static void main(String[] args) {
        
        //测试increment主键生成
        Customer5Demo demo = new Customer5Demo();
        Customer5 customer5 = new Customer5();
        demo.saveCustomer5IDByIdentity(customer5, "华山", "580");
        //测试查询结果
        List list = demo.queryAllCustomer5();
        for (int i = 0; i < list.size(); i++) {
            Customer5 customer  = (Customer5)list.get(i);
            System.out.println(customer.getCustomerID()+customer.getName()+customer.getPhone());
        }
        HibernateSessionFactory.closeSession();
        
    }
    
    //下面是封装保存
    public void saveCustomer5IDByIdentity(Customer5 customer5,String name,String phone) {
        customer5.setName(name);
        customer5.setPhone(phone);
        session.save(customer5);
        //一定一定要记得提交事务
        tran.commit();
    }
    //下面是封装查询
    @SuppressWarnings("rawtypes")
    public List queryAllCustomer5(){
        /**由会话工厂类创建一个会话Session对象**/
        Session session = HibernateSessionFactory.getSession();
        /**由会话session对象创建一个查询对象**/
        Query query = session.createQuery("from bean.Customer5");
        List list = query.list();
        HibernateSessionFactory.closeSession();
        return list;
    }
}

 思考:生成机器码有什么作用?

posted @ 2019-05-30 22:53  CiscoLee  阅读(1038)  评论(0编辑  收藏  举报