hibernate入门一之如何使用hibernate创建数据表

引言:使用连接数据库来创建实体类,很快就学会了,但是对于怎么用hibernate创建数据表确实用了两天的时间,记录下这次学习的过程。

1、在一开始怎么都搜不到资料,后来才明白,在搜的时候要加正向的,用数据库创建实体类是反向,用实体类创建数据表是正向的,这样搜就可以了

2、在一开始的时候,总是执着于IDE和插件的问题,对于所遇到的问题没有进行深入的研究,导致浪费掉了大量的时间(最后还是没搞定)

3、总是执着于教程上的操作方式,到最后才发现,在新版本里的写法是不一样的,坑之又坑

4、浪费时间最长的是如何使用hibernate用实体类生成hbm.xml文件,在教程里看老师用的挺溜的,因为电脑的原因,ide、插件安装失败,所以最后是只能是手写了

1、创建hibernate项目:参考资料:https://blog.csdn.net/fighting_sxw/article/details/80566295(友情提示:注意测试时新版本与旧版本的书写方式)

2、在使用hibernate创建数据表需要四个主要文件:实体类,实体类对应的映射文件(后缀名为hbm.xml结尾),hibernate的配置文件(以cfg.xml结尾),以及测试类

3、对应的主要内容如下:

实体类:

package com.hibernate.entity;


import java.util.Date;

public class Students {

    private int sid;
    private String sname;
    private String gender;
    private Date birthday;
    private String address;

    public Students(){

    }

    public Students(int sid, String sname, String gender, Date birthday, String address) {
        this.sid = sid;
        this.sname = sname;
        this.gender = gender;
        this.birthday = birthday;
        this.address = address;
    }

    public int getSid() {
        return sid;
    }

    public void setSid(int sid) {
        this.sid = sid;
    }

    public String getSname() {
        return sname;
    }

    public void setSname(String sname) {
        this.sname = sname;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "Students{" +
                "sid=" + sid +
                ", sname='" + sname + '\'' +
                ", gender='" + gender + '\'' +
                ", birthday=" + birthday +
                ", address='" + address + '\'' +
                '}';
    }
}

 实体类对应的hbm.xml文件

<?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.hibernate.entity.Students" table="Students">
        <id name="sid" type="int">
            <column name="SID"/>
            <generator class="assigned"/>
        </id>
        <property name="sname" type="java.lang.String">
            <column name="SNAME"/>
        </property>
        <property name="gender" type="java.lang.String">
            <column name="GENDER"/>
        </property>
        <property name="birthday" type="java.util.Date">
            <column name="BIRTHDAY"/>
        </property>
        <property name="address" type="java.lang.String">
            <column name="ADDRESS"/>
        </property>

    </class>


</hibernate-mapping>

 hibernate的cfg文件

<?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.url">jdbc:mysql://localhost:3306/rushi</property>
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="connection.username">root</property>
    <property name="connection.password">Sys935269</property>

    <!-- DB schema will be updated if needed -->
    <!-- <property name="hbm2ddl.auto">update</property> -->
    <property name="show_sql">true</property>
    <property name="format_sql">true</property>
    <!--自动生成-->
    <property name="hbm2ddl.auto">create</property>
    <!--数据库方言-->
    <property name="hibernate.dialect">org.hibernate.dialect.MySQL55Dialect</property>

    <!--加载资源-->
    <mapping resource="com/hibernate/entity/Students.hbm.xml"/>

  </session-factory>
</hibernate-configuration>

 4、这里对测试类重点介绍下,测试的时候新版本与旧版本可能会有所不同,按照教程可能永远都找不出问题所在(参考资料:https://blog.csdn.net/bingjianit/article/details/68954250

package com.hibernate.entity;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.junit.After;
import org.junit.Before;

import java.util.Date;

public class Test {

    private SessionFactory sessionFactory;
    private Session session;
    private Transaction transaction;

    @Before
    public void init() {

        //创建配置对象
        //Configuration configure = new Configuration().configure();

        //创建服务注册对象
        //ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();

        ////以上为旧版本的写法,若是不注意,就会报org.hibernate.MappingException: Unknown entity: com.hibernate.entity.Student这个错误

        StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure().build();
        //创建会话工厂对象
        SessionFactory sessionFactory = new MetadataSources(serviceRegistry).buildMetadata().buildSessionFactory();
        //会话对象
        session = sessionFactory.openSession();
        //开启事务
        transaction = session.beginTransaction();
    }

    @After
    public void destory() {
        //提交事务
        transaction.commit();
        //关闭会话
        session.close();
        //关闭会话工厂
        sessionFactory.close();
    }

    @org.junit.Test
    public void TestSaveStudents() {
        //生成学生对象
        Students s = new Students(2, "张三丰", "南", new Date(), "武当山");
        session.save(s);
    }
}

 程序运行结束,可能提示运行失败,但是数据已经存在表格里了,不确定的可以去数据里查看下

 

 

 

 

 

 

 

 

格言:从不熟悉到熟悉是一个过程,无需恐惧,

 

posted @ 2019-06-08 13:31  绛珠仙草林黛玉  阅读(1843)  评论(0编辑  收藏  举报