使用Eclipse创建Hibernate工程

来源:https://www.cnblogs.com/sky230/p/5876589.html

创建一个java project项目,加入hibernate的jar包和数据库驱动包,并引入到项目。数据包可以到

http://hibernate.org/去下载 hibernate-release-5.3.2.Final.zip,解压后在 hibernate-release-5.3.2.Final\lib\required,

目录下有这些

下面是4.2.4版本的。

在eclipse上安装hibernate tools插件。

Eclipse的“Help”-->"Eclipse Marketplace", 输入hibernate查找,因为Hibernate是JBoss的一种,所以安装的是JBoss Tools,安装的时候只选择Hiberante Tools即可。

HibernateTools的安装完成!选择工程下的SRC目录,然后右键 New->Other->Hibernate->Hibernate Configuration File(cfg.xml)。这一步只是测试有没有安装好工具,不需要创建任何东西。

hibernate开发步骤:

1. 创建hibernate配置文件(hibernate.cfg.xml)

选择工程下的SRC目录,然后右键 New->Other->Hibernate->Hibernate Configuration File(cfg.xml)

hibernate.cfg.xml

复制代码

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!-- 1. 配置连接数据库的基本信息 -->
        <property name="connection.username">root</property>        
        <property name="connection.password">123456</property>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql:///test</property>
        
        <!-- 2. 配置hibernate 的基本信息 -->
        <!-- hibernate 所使用的数据库方言 -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>
        
        <!-- 执行操作时是否在控制台打印SQL -->
        <property name="show_sql">true</property>
        
        <!-- 是否对SQL 进行格式化 -->
        <property name="format_sql">true</property>
        
        <!-- 指定自动生成数据表的策略 -->
        <property name="hbm2ddl.auto">update</property>
        
         <!-- 指定关联的 .hbm.xml 文件 -->
        <mapping resource="com/home/hibernate/User.hbm.xml"/> 
        
    </session-factory>
</hibernate-configuration>

复制代码

这步配置hibernate连接数据库的基本信息,并关联 .hbm.xml文件。

2. 创建持久化类(普通的类)(Persistent Objects)

复制代码

package com.home.hibernate;

/**
 * 一般在javaBean类
 *
 * @author Sky
 * @date 2016年9月16日
 */
public class User {
    private int userId;
    private String userName;
    private String password;
    private String email;
    private String address;
    
    public int getUserId() {
        return userId;
    }
    public void setUserId(int userId) {
        this.userId = userId;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public User(String userName, String password, String email, String address) {
        super();
        this.userName = userName;
        this.password = password;
        this.email = email;
        this.address = address;
    }
    public User() {
        super();
    }
    @Override
    public String toString() {
        return "User [userId=" + userId + ", userName=" + userName + ", password=" + password + ", email=" + email
                + ", address=" + address + "]";
    }
    
}

复制代码

3. 创建对象-关系映射文件(*.hbm.xml)

或:

右键某个类会默认为该类创建 hbm.xml 文件。

复制代码

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2016-9-16 23:47:20 by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping>
    <class name="com.home.hibernate.User" table="USER">
        <id name="userId" type="int">
            <column name="USERID" />
            <!-- 指定主键生成方式。assigned:主键是自己定的,不是数据库生成的。native:使用数据库本地方式 -->
            <generator class="assigned" />
        </id>
        <property name="userName" type="java.lang.String">
            <column name="USERNAME" />
        </property>
        <property name="password" type="java.lang.String">
            <column name="PASSWORD" />
        </property>
        <property name="email" type="java.lang.String">
            <column name="EMAIL" />
        </property>
        <property name="address" type="java.lang.String">
            <column name="ADDRESS" />
        </property>
    </class>
</hibernate-mapping>

复制代码

这些信息会根据写的javaBean类(即User类)自动生成。

4. 通过HibernateAPI编写访问数据库的代码

创建一个JUnit Test Class来进行测试

package com.home.hibernate;

import static org.junit.Assert.*;

import javax.imageio.spi.ServiceRegistry;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.Test;

public class HibernateTest {

    @Test
    public void test() {
        //1. 创建一个SessionFactory 对象
        SessionFactory sessionFactory = null;
        
        //1).创建 Configuration 对象:对应 Hibernate 的基本配置信息和对象关系映射信息(关联hibernate.cfg.xml文件)
//        Configuration configuration = new Configuration().configure("hibernate.cfg.xml");
        Configuration configuration = new Configuration().configure(); //因为使用默认的命名,所以不用指定也可以
        
        //4.0 之前这样创建
//        sessionFactory = configuration.buildSessionFactory();
        
        //2).创建一个 ServiceRegistry 对象:这是hibernate 4.x 新添加的对象
        //   hibernate 的任何配置和服务都需要在该对象中注册后才能有效。
        org.hibernate.service.ServiceRegistry serviceRegistry = 
                new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
        
        //3).
        sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        
        //2. 创建一个 Session 对象
        Session session = sessionFactory.openSession();
        
        //3. 开启事务
        Transaction transaction = session.beginTransaction();
        
        //4. 执行保存操作
        User user = new User("Sky","333","[email protected]","厦门");
        session.save(user);
        
        //5. 提交时务
        transaction.commit();
        
        //6. 关闭 Session
        session.close();
        //7. 关闭 SessionFactory 对象
        sessionFactory.close();
        
    }
}

但是在运行时,出错,得不到正确的结果。为什么呢?是因为版本的问题,本文写得是用4.2.2版本的hibernate,但是我在实验时是使用的5.3.2的版本。所以,在代码上就不一样。

下面是5.3.2版本的hibernate的代码:

package com.home.hibernate;

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.model.naming.ImplicitNamingStrategyComponentPathImpl;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.junit.Test;

public class HibernateTest {

    @Test
    public void test() {
        //1. 创建一个SessionFactory 对象
        SessionFactory sessionFactory = null;
        
        //1).创建 Configuration 对象:对应 Hibernate 的基本配置信息和对象关系映射信息(关联hibernate.cfg.xml文件)
//        Configuration configuration = new Configuration().configure("hibernate.cfg.xml");
        Configuration configuration = new Configuration().configure(); //因为使用默认的命名,所以不用指定也可以
        
        //4.0 之前这样创建
//        sessionFactory = configuration.buildSessionFactory();
        
        //2).创建一个 ServiceRegistry 对象:这是hibernate 4.x 新添加的对象
        //   hibernate 的任何配置和服务都需要在该对象中注册后才能有效。
        StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder().configure().build();
        Metadata metadata = new MetadataSources(standardRegistry).getMetadataBuilder()
                .applyImplicitNamingStrategy(ImplicitNamingStrategyComponentPathImpl.INSTANCE).build();

        //3).        
        sessionFactory = metadata.getSessionFactoryBuilder().build();
       
        //2. 创建一个 Session 对象
        Session session = sessionFactory.openSession();
        
        //3. 开启事务
        Transaction transaction = session.beginTransaction();
        
        //4. 执行保存操作
        User user = new User("Sky","333","[email protected]","厦门");
        session.save(user);
        
        //5. 提交时务
        transaction.commit();
        
        //6. 关闭 Session
        session.close();
        //7. 关闭 SessionFactory 对象
        sessionFactory.close();
        
    }

}
 

运行后MySQL的结果:

控制台也有SQL语句生成,因为前面的配置文件有设置:

<property name="show_sql">true</property>

数据库部分:hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
    <property name="myeclipse.connection.profile">Mysql</property>
    <property name="connection.url">jdbc:mysql://localhost:3306/test</property>
    <property name="connection.username">root</property>
    <property name="connection.password">123456</property>
    <property name="connection.driver_class">
        com.mysql.jdbc.Driver
    </property>
    <property name="dialect">
        org.hibernate.dialect.MySQL5Dialect
    </property>
    <property name="format_sql">true</property>
    <property name="show_sql">true</property>
    <property name="hbm2ddl.auto">update</property>
    <mapping  resource="com/home/hibernate/User.hbm.xml" />
</session-factory>

</hibernate-configuration>

整个项目目录:

猜你喜欢

转载自blog.csdn.net/jintingbo/article/details/81181493