zoukankan      html  css  js  c++  java
  • hibernate入门-------实例、increment生成方式【实例自增-避免使用】【第二天】

    经过前面学习,和前面的代码基本一致。只需要将前面的代码修改/增加类,复用修改少量就可以达到效果。

    请对比前两个实例。

    一、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"/>
        </session-factory>
    </hibernate-configuration>

    二、Customer3.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.Customer3" table="customers3" catalog="test">
           <id name="customerID" type="java.lang.Integer">
               <column name="customerID"/>
               <generator class="increment"></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>

    三、Customer3.java

    package bean;
    
    //验证identity生成主键方式的映射类,数据库对应表customers2
    public class Customer3 {
        private int customerID;
        private String name,phone;
        
        public int getCustomerID() {
            return customerID;
        }
    
        public void setCustomerID(int 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();
            }
        }
    }

    五、Customer3Demo.java

    package bean;
    
    import java.util.List;
    
    
    
    
    import hibernate.factory.HibernateSessionFactory;
    
    import org.hibernate.Session;
    import org.hibernate.Transaction;
    import org.hibernate.query.Query;
    
    
    //用于测试identity主键生成方式,增加记录
    //由于是增加数据,所以不需要写Query,只需要new表,增加数据即可
    public class Customer3Demo {
        Session session = HibernateSessionFactory.getSession();
        Transaction tran = session.beginTransaction();
        public static void main(String[] args) {
            
            //测试identity主键生成
            Customer3Demo demo = new Customer3Demo();
            Customer3 customer3 = new Customer3();
            demo.saveCustomer3IDByIdentity(customer3, "华山", "580");
            //测试查询结果
            List list = demo.queryAllCustomer3();
            for (int i = 0; i < list.size(); i++) {
                Customer3 customer  = (Customer3)list.get(i);
                System.out.println(customer.getCustomerID()+customer.getName()+customer.getPhone());
            }
            HibernateSessionFactory.closeSession();
            
        }
        
        //下面是封装保存
        public void saveCustomer3IDByIdentity(Customer3 customer3,String name,String phone) {
            customer3.setName(name);
            customer3.setPhone(phone);
            session.save(customer3);
            //一定一定要记得提交事务
            tran.commit();
        }
        //下面是封装查询
        @SuppressWarnings("rawtypes")
        public List queryAllCustomer3(){
            /**由会话工厂类创建一个会话Session对象**/
            Session session = HibernateSessionFactory.getSession();
            /**由会话session对象创建一个查询对象**/
            Query query = session.createQuery("from bean.Customer3");
            List list = query.list();
            HibernateSessionFactory.closeSession();
            return list;
        }
    }

    总结:经过上面的例子和之前的比较,不难得出结论。甚至可以思考必要的方法整合。将创建表、创建数据库、数据查询等简化,然后打包。后面只需配置数据,就可以完成与数据库交互的功能。这个问题先提出来,后续考虑。现在开始继续学习。

  • 相关阅读:
    读书笔记之理想设计的特征
    一些javascript 变量声明的 疑惑
    LINQ 使用方法
    Google MySQL tool releases
    读书笔记之设计的层次
    EF之数据库连接问题The specified named connection is either not found in the configuration, not intended to be used with the Ent
    转载 什么是闭包
    javascript面向对象起步
    Tips
    数据结构在游戏中的应用
  • 原文地址:https://www.cnblogs.com/ciscolee/p/10952397.html
Copyright © 2011-2022 走看看