搭建hibernate环境 使用JDBC连接数据库

搭建hibernate环境 使用JDBC连接数据库

1.新建一个java项目(测试用)

2.导入hibernate所需的jar包

搭建hibernate环境 使用JDBC连接数据库_第1张图片

    // hibernate所需jar包
    antlr-2.7.7.jar
    dom4j-1.6.1.jar
    hibernate-commons-annotations-4.0.5.Final.jar
    hibernate-core-4.3.11.Final.jar
    hibernate-jpa-2.1-api-1.0.0.Final.jar
    jandex-1.1.0.Final.jar
    javassist-3.18.1-GA.jar
    jboss-logging-3.1.3.GA.jar
    jboss-logging-annotations-1.2.0.Beta1.jar
    jboss-transaction-api_1.2_spec-1.0.0.Final.jar

    // 连接mysql数据库驱动包
    mysql-connector-java-5.1.20-bin.jar

3.配置hibernate.cfg.xml文件:

配置文件所放位置:

放在src下目录下

查找方式:

文件的获取:在jar包:hibernate-release-版本号.Final\project\etc 目录下

hibernate.cfg.xml配置文件代码,例如:

'1.0' encoding='utf-8'?>
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">


    
        
        "connection.driver_class">
            org.gjt.mm.mysql.Driver
        
        "connection.url">jdbc:mysql:///hibernate4
        "connection.username">root
        "connection.password">123456

        
        
        "dialect">
            org.hibernate.dialect.MySQL5Dialect
        
        
        "show_sql">true
        
        "format_sql">true
        
        "cn/hibernate/entity/score.hbm.xml" />
    

4.配置映射文件 xxx.hbm.xml文件:

'1.0' encoding='utf-8'?>
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
"cn.hibernate.entity">
    <class name="Score">
        <id name="id">
            <generator class="native">generator>
        id>

        <property name="stuId"/>
        <property name="subjectId"/>
        <property name="result"/>
    class>
hibernate-mapping>

5.HibernateUitl工具类:

用于加载hibernate.cfg.xml配置文件:

package cn.hibernate.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

/**
 * hibernate工具类
 * @author tang
 *
 */
public class HibernateUitl {

    private static Configuration cfg = null;
    private static SessionFactory factory = null;
    private static Session session = null;

    static {
        cfg = new Configuration().configure();
        factory = cfg.buildSessionFactory(new StandardServiceRegistryBuilder().applySettings(cfg.getProperties())
                    .build());
    }

    public static Session getSession() {
        if(factory != null) {
            return factory.openSession();
        }else{
            factory = cfg.buildSessionFactory(new StandardServiceRegistryBuilder().applySettings(cfg.getProperties())
                    .build());
        }
        return factory.openSession();
    }

    public static void closeSession() {
        if(session != null && session.isOpen()){
            session.close();
        }
    }
}

6.添加对应映射文件(xxx.hbm.xml)的实体类:

// 实体类
public class Score {
    private int id;
    private int stuId;//学生编号
    private int subjectId;//科目编号
    private double result;//成绩
    // 省略 gettersetter 方法
}

7.测试类:

public class HibernateTest {

    @Test
    public void createDB() {
        Configuration cfg = new Configuration().configure();
        SchemaExport se = new SchemaExport(cfg);
        //第一个参数是否生成ddl脚本,第二个参数是否执行到数据库中
        se.create(true, true);
    }

    @Test
    public void sqlSave() throws Exception {
        Session session = null;
        Transaction tx = null;
        try {
            session = HibernateUitl.getSession();
            tx = session.beginTransaction();

            Score s = new Score();
            s.setId(1);
            s.setSubjectId(2);
            s.setResult(89);

            session.save(s);

            tx.commit();
        } catch (Exception e) {
            if(tx != null)
                tx.rollback();
            e.printStackTrace();
            throw e;
        }finally{
            HibernateUitl.closeSession();
        }
    }
}

你可能感兴趣的:(java基础,hibernate)