美文网首页
Hibernate入门实例

Hibernate入门实例

作者: 小格zZZ | 来源:发表于2018-12-02 12:59 被阅读0次

    创建Hibernate框架的程序大致步骤

    • 创建java项目
    • 为hibernate添加jar文件
    • 创建持久类
    • 创建持久类的映射文件
    • 创建配置文件
    • 创建检索或存储持久对象的类
    • 运行应用程序

    环境说明

    • 编译器 idea
    • 数据库 MySQL 8.013
    • Java JDK8
    • Hibernate版本 5.2.12

    准备工作

    • 创建一个数据表
    CREATE TABLE tb_employee (
      id int(10) unsigned NOT NULL AUTO_INCREMENT,
      firstName varchar(32) NOT NULL DEFAULT '',
      lastName varchar(32) NOT NULL DEFAULT '',
      PRIMARY KEY (id)
    ) 
    

    实例创建

    • 创建项目

      勾选Hibernate框架,并且勾选创建创建默认配置文件 创建带有hibernate框架的项目 为项目命名后,添加lib 添加Hibernate相关文件作为一个库 添加Hibernate库 添加lib
      添加lib
    • 创建持久化类
    public class Employee {
        private int id;
        private String firstName;
        private String lastName;
         //get和set方法此处省略
    }
    
    • 创建持久化类的映射文件
      创建映射文件,必须在实体类所在包的外部。其中实体类与表一一对应,创建的Employee实体类与之前创建的表进行对应,这个用table进行了声明;id是表的主键,并且创建表的时候是自增的,用id与generator标签进行封装;其他的两个属性声明即可。
    <?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.mypackage.Employee" table="tb_employee">  
            <id name="id">  
                <generator class="assigned"></generator>  
            </id>  
        <property name="firstName"></property>  
        <property name="lastName"></property>  
        </class>  
    </hibernate-mapping>
    
    • 修改配置文件
      因为我们之前在创建工程的时候就勾选了自动创建模板配置文件,所以这个时候对其参数进行修改就ok
    <?xml version='1.0' encoding='utf-8'?>
    <!DOCTYPE hibernate-configuration PUBLIC
            "-//Hibernate/Hibernate Configuration DTD//EN"
            "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
    <hibernate-configuration>
    <session-factory>
        <!--数据库连接的相关参数-->
        <property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost/my?serverTimezone=UTC</property>
        <property name="connection.username">root</property>
        <property name="connection.password">123456</property>
        <!--数据库版本对应的方言-->
        <property name="dialect">org.hibernate.dialect.MySQL8Dialect</property>
        <!--是否显示生成的HQL语句-->
        <property name="show_sql">true</property>
        <!--映射实体类配置文件-->
        <mapping resource="employee.hbm.xml"/>
        <!-- DB schema will be updated if needed -->
        <!-- <property name="hbm2ddl.auto">update</property> -->
    </session-factory>
    </hibernate-configuration>
    
    这里需要注意的是,一定要在url链接后添加serverTimezone参数,否则会报下面的错误 时区错误
    • 创建运行测试类
    public class Main {
        private static final SessionFactory ourSessionFactory;
    
        //从配置文件读取参数构建会话工厂
        static {
            try {
                ourSessionFactory = new Configuration().
                        configure("hibernate.cfg.xml").
                        buildSessionFactory();
            } catch (Throwable ex) {
                throw new ExceptionInInitializerError(ex);
            }
        }
    
        //构建会话
        public static Session getSession() throws HibernateException {
            return ourSessionFactory.openSession();
        }
    
        public static void main(final String[] args) throws Exception {
            final Session session = getSession();
            try {
                Transaction t=session.beginTransaction();
                Employee e1=new Employee();
                e1.setFirstName("Max");
                e1.setLastName("Su");
                //持久化对象到数据库
                session.persist(e1);//persisting the object
                t.commit();//transaction is committed
            } finally {
                session.close();
                System.out.println("successfully saved");
            }
        }
    }
    
    • 运行结果

      会自动生成HQL语句 运行结果 数据库查询结果(这是运行了两次的结果) 数据库记录

    相关文章

      网友评论

          本文标题:Hibernate入门实例

          本文链接:https://www.haomeiwen.com/subject/kqrjcqtx.html