初识hibernate

一、初识hibernate

第一次系统的学习hibernate,做了一个demo来了解一下hibernate的使用过程。首先hibernate是一个主流的ORM框架。通过使用hibernate简化了传统JDBC的操作,使得程序员可以使用面向对象的思维来操纵数据库。

优点

  • 程序更加面向对象
  • 提高了生产率
  • 方便移植(修改配置文件)
  • 无侵入性

    缺点

  • 效率比JDBC略差
  • 不适合批量操作

    与Mybati比较

  • Hibernate和MyBatis都是ORM框架,为数据层提供了持久化操作支持
  • 相对于MyBatis的“SQL-Mapping”的ORM实现,Hibernate的ORM实现更加完善,提供了对象状态管理、级联操作等功能
  • 完全面向对象,语句与数据库无关,开发者无需关注SQL的生成,开发简单,便于修改,数据库移植性好
  • 由于直接使用SQL,MyBatis使用自由度较高。在不考虑缓存的情况下,MyBatis的执行效率高于Hibernate。

二、第一个hibernate程序

1.创建项目并导入Jar包

我使用的编辑器是IntelliJ Idea,新建一个HibernateDemo项目,在项目中引入hibernate所需要的jar包以及mysql驱动。

hibernate可以从官方网站获取网址为:http://hibernate.org

解压缩后hibernate所需要的jar包在目录下的/lib/required中。

我使用的hibernate为5.2.16版本结构如下:

CN3f8f.png

2.创建数据库及表

在Mysql中创建一个名称为hibernate的数据库,在此数据库中创建一张名为customer的表,表的结构如下图
CN8NLQ.md.jpg

3.编写实体类

在项目的src建立包,并在包中创建实力类Customer,Customer类包含于customer报表中字段对应的属性,而且要加上setter和getter方法。
Customer.java

package com.test.bean;

public class Customer {

    private Integer id;
    private String name;
    private String gender;
    private Integer age;
    private String city;

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getGender() {
        return gender;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }
}

4.编写映射文件

在实体类的包下,创建一个名称与类名相同的Customer.hbm.xml文件,通过这个文件实现类与数据库中的表建立联系。在打开hibernate.core包找到hibernate-mapping-3.0.dtd文件。在文件的上方有文件dtd信息,可以复制配置文件中。这样编辑配置文件会提示信息。

<hibernate-mapping package="com.test">
    <class name="com.test.bean.Customer" table="customer">
        <id name="id" column="id">
            <!--根据底层数据库主键自动增长-->
            <generator class="native"/>

        </id>
        <!--非主键映射,属性和列名一一对应-->
        <property name="name" column="name"/>
        <property name="gender" column="gender"/>
        <property name="age" column="age"/>
        <property name="city" column="city"/>
    </class>
</hibernate-mapping>

5.编写核心配置文件

在src目录下建立hibernate.cfg.xml文件,这个文件主要用来配置数据库的连接以及hibernate运行时所需要的各个属性的值。可以在hibernate压缩包下/project/etc下找到简要的hibernate.cfg.xml文件,配置信息可以参考同目录下的hibernate.properties文件。同样在hibernate.core包中可以找到hibernate.cfg.xml的约束性文件hibernate-configuration-3.0.dtd

<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <!--显示sql语句-->
        <property name="show_sql">true</property>
        <!--指定方言-->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <!--数据库的用户名-->
        <property name="hibernate.connection.username">root</property>
        <!--数据库的密码-->
        <property name="hibernate.connection.password">123456</property>
        <!--数据库的driver-->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <!--数据库的url-->
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate</property>
        <!--关联的hbm配置文件-->
        <mapping resource="com/test/bean/Customer.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

6.进行测试

hibernate的配置基本已经搭建完成,下面来向数据库中存入条数据测试hibernate是否搭建成功。


import com.test.bean.Customer;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class Test {


    public static void main(String[] args) {

        Configuration config = new Configuration().configure();//加载配置文件
        SessionFactory factory = config.buildSessionFactory();//创建Session工厂对象
        Session session = factory.openSession();//得到Session对象
        Transaction t =  session.beginTransaction();//开启事务

        Customer c = new Customer();
        c.setName("Marry");
        c.setGender("F");
        c.setAge(18);
        c.setCity("Harbin");
        session.save(c);

        t.commit();//将对象保存至数据库
        session.close();

    }


}

数据插入成功

CNN94s.md.jpg

三、过程中遇到的问题

在初次运行hibernate的测试类时报了以下错误

Exception in thread "main" org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:271)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:233)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
    at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:51)
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:242)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.handleTypes(MetadataBuildingProcess.java:352)
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:111)
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.build(MetadataBuildingProcess.java:83)
    at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:418)
    at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:87)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:691)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:726)
    at Test.main(Test.java:14)
Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
    at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.determineDialect(DialectFactoryImpl.java:100)
    at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(DialectFactoryImpl.java:54)
    at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:137)
    at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35)
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:88)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:259)
    ... 14 more

原因是创建Configuration对象时只是简单的new Configuration(),导致没有加载hibernate的全局配置文件,要使用new Configure().config()来创建Configuration对象才能成功加载。

四、总结

通过一个简单的hibernate例子,完成了hibernate的搭建和向数据库中存入数据,虽然例子很简单但了解了hibernate开发的简单流程。希望通过这个例子由浅入深在以后的学习过程中更加深入的了解hibernate。

猜你喜欢

转载自www.cnblogs.com/RicardoWX/p/8994199.html