PinkGuy / Hibernate搭建步骤
Created 2019-11-29 Modifyd 2019-11-29

449 Words

1.导入相关的jar包

![jar]()

2.配置hibernate主配置

  • 创建名字默认hibernate.cfg.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <!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>
        <!-- 1.配置数据库信息 -->
        <!--必须有的 -->
        <property name="connection.url">
            jdbc:oracle:thin:@192.168.206.1:1521:orcl
        </property>
        <property name="connection.driver_class">
            oracle.jdbc.driver.OracleDriver
        </property>
            
        <property name="connection.username">scott</property><!-- 用户 -->
        <property name="connection.password">333</property><!-- 密码 -->
    
        <property name="dialect">
            org.hibernate.dialect.ProgressDialect
        </property>
            
        <!-- 辅助文件 -->
        <property name="show_sql">true</property>   <!-- 输出底层sql语句 -->
    		<property name="format_sql">true</property> <!-- 输出底层sql语句格式 -->
            
    		<!-- 添加映射文件 -->
        <mapping resource="dept.hbm.xml"/>
    </session-factory>
    </hibernate-configuration>
    

3.测试配置是否正常

  • 工具类

    public class Hibernate {
    static SessionFactory factory;
    static Session session = null;
    static {
        Configuration cfg = new Configuration().configure();
        factory = cfg.buildSessionFactory();
    }
    
    public  static  Session getSession(){
        if (session == null) session =factory.openSession();
        return  session;
    }
    }
    
  • 测试类

    public class TestHb {
    public static void main(String[] args) {
        Session session  = Hibernate.getSession();
        System.out.println(session);
    }
    }
    

4.创建实体类映射文件

  • 配置实体类与数据库表的一一对应关系,映射关系
  • 建议命名 .hbm.xml;
  • 建议column里用大写

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
    <hibernate-mapping>
    <class name="com.hb.entity.Dept" >  <!-- 实体类的全类名 -->
        <id name="deptno" column="DEPTNO">  <!-- 设置主键 -->
            <generator class="assigned"></generator> <!-- 手动增长 -->
        </id>
        <property name="dname" column="DNAME"/>
        <property name="loc" column="LOC"/>
    </class>
    </hibernate-mapping>
    
5.获取session使用hibernate
 Transaction tx = session.beginTransaction(); //获取提交事务对象
 Session session = Hibernate.getSession();
        Dept dept = new Dept(50,"阿里","杭州");
   session.save(dept);
  tx.commit();
  System.out.println("数据添加成功");