Java 杂谈

Hibernate学习笔记 | 使用IDEA创建第一个Hiber

2019-08-08  本文已影响3人  一颗白菜_

创建项目

打开IDEA,选择New Project,选择Hibernate,点击下一步


取名为test3,点击Finish,然后等待一下后创建项目成功


创建成功

新建一个包:com.cerr.hibernate.helloworld

连接数据库

先点击右边的Database,再点击加号,Data Source,MySQL。



如果右边没有显示Database的话,可以如下操作进行显示



然后填好对应的信息后点击Test Connection看看数据库是否能成功连接。

如果使用的不是MySQL8.0以上的话在连接数据库时会报错08001
只需点击MYSQL更换数据库版本即可



更换版本

我是更换到5.1.47就可以了

创建持久化类的映射文件

点击左边的Persistence,然后进行如下操作。


点击OK之后就创建成功了,为了编程方便,我们手动的对News类加上一个有参构造器和无参构造器,添加后代码如下:

package com.cerr.hibernate.helloworld;

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import java.util.Date;
import java.util.Objects;

@Entity
public class News {
    private int id;
    private String title;
    private String author;
    private Date date;

    public News() {
    }

    @Id
    @Column(name = "id")
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @Basic
    @Column(name = "title")
    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    @Basic
    @Column(name = "author")
    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    @Basic
    @Column(name = "date")
    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        News news = (News) o;
        return id == news.id &&
                Objects.equals(title, news.title) &&
                Objects.equals(author, news.author) &&
                Objects.equals(date, news.date);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, title, author, date);
    }

    public News(String title, String author, Date date) {
        this.title = title;
        this.author = author;
        this.date = date;
    }
}

对应的映射文件:

<?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>

    <class name="com.cerr.hibernate.helloworld.News" table="news" schema="hibernate5">
        <id name="id" column="id"/>
        <property name="title" column="title"/>
        <property name="author" column="author"/>
        <property name="date" column="date"/>
    </class>
</hibernate-mapping>

配置hibernate.cfg.xml文件

首先我们应该把java的数据库驱动jar包加入,加入mysql-connector-java-5.1.47-bin.jar包。
然后打开hibernate.cfg.xml文件,目前该文件如下:

<?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/hibernate5</property>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <mapping resource="com/cerr/hibernate/helloworld/News.hbm.xml"/>
        <mapping class="com.cerr.hibernate.helloworld.News"/>
        <!-- <property name="connection.username"/> -->
        <!-- <property name="connection.password"/> -->

        <!-- DB schema will be updated if needed -->
        <!-- <property name="hibernate.hbm2ddl.auto">update</property> -->
    </session-factory>
</hibernate-configuration>

我们需要加入一些配置,例如账号密码等..,添加后如下:

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

        <!-- 配置hibernate的基本信息-->
        <!-- hibernate所使用的的数据库方言 -->
        <property name="dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>
        <!-- 执行操作时是否在控制台打印SQL-->
        <property name="show_sql">true</property>
        <!-- 是否对SQL进行格式化-->
        <property name="format_sql">true</property>
        <!-- 指定生成数据表的策略-->
        <property name="hibernate.hbm2ddl.auto">update</property>
        <mapping resource="com/cerr/hibernate/helloworld/News.hbm.xml"/>
        <mapping class="com.cerr.hibernate.helloworld.News"/>
        
    </session-factory>
</hibernate-configuration>

测试

新建一个测试类NewsTest.java

package com.cerr.hibernate.helloworld;

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

import java.util.Date;

public class NewsTest {
    public static void main(String[] args) {
        //创建一个Configuration对象
        //Configuration对象对应于Hibernate的基本配置信息和对象关系映射文件
        Configuration configuration = new Configuration().configure();
        //创建一个SessionFactory对象
        SessionFactory sessionFactory = configuration.buildSessionFactory();

        //创建一个Session对象
        Session session = sessionFactory.openSession();
        //开启事务
        Transaction transaction = session.beginTransaction();
        //执行保存操作
        News news = new News("java","cerr",new Date(new java.util.Date().getTime()));
        session.save(news);
        //提交事务
        transaction.commit();
        //关闭Session
        session.close();
        //关闭SessionFactory
        sessionFactory.close();
    }
}

运行后成功。
下面我们进行解析


关于创建持久化类

关于对象关系映射文件

Hibernate采用XML格式的文件来指定对象和关系数据之间的映射,在运行时Hibernate将根据这个映射文件来生成各种SQL语句。映射文件的扩展名为.hbm.xml

Configuration类

SessionFactory接口

//创建一个Configuration对象
//Configuration对象对应于Hibernate的基本配置信息和对象关系映射文件
Configuration configuration = new Configuration().configure();
//创建一个SessionFactory对象
SessionFactory sessionFactory = configuration.buildSessionFactory();

Session接口

Session是应用程序与数据库之间交互操作的一个单线程对象,是Hibernate运作的中心,所有持久化对象必须在session的管理下才可以进行持久化操作,此对象的生命周期很短,Session对象有一个一级缓存。Session相当于JDBC中的Connection

Transaction(事务)

代表一次原子操作,它具有数据库事务的概念。所有持久化层都应该在事务管理下执行,即使是只读操作。
开启事务:Transaction tx = session.beginTransaction();
常用方法:
commit():提交相关联的session实例
rollback():撤销事务操作
wasCommitted():检查事务是否提交

Hibernate配置文件的两个配置项

上一篇 下一篇

猜你喜欢

热点阅读