Hibernate5环境搭建

Hibernate5
环境:Window7,jdk1.7,tomcat7,eclipse4.5
环境搭建
1.导入hibernate的jar包
- hibernate-release-5.0.12.Finallib equired
- hibernate-release-5.0.12.Finallibjpa
- 日志和mysql驱动的jar包4个

2. 创建实体类,hibernate可以自动创建表

3.配置实体类和数据库表一一对应关系(映射关系)
- 建议:在实体类所在的包创建--实体类名称.hbm.xml
- 配置xml格式 ,引入dtd约束 <hibernate-core/orghibernate>

- 配置映射关系:
<hibernate-mapping>
    <!-- 1.配置类和表对应
        class标签
        name属性:实体类全路径
        table属性:数据库表名称
    -->
    <class name="com.ants.entity.User" table="t_user">
        <!-- 2.配置实体类id和表id对应
            hibernate要求实体类有一个属性唯一值
            hibernate要求表有字段作为唯一值
        -->
        <!-- id标签
            name属性:实体类里面id属性名称
            column属性:生成的表字段名称
        -->
        <id name="uid" column="uid">
            <!-- 设置数据库表id增长策略
                native:生成表id值就是主键自动增长
            -->
            <generator class="native"></generator>
        </id>
        <!-- 配置其他属性和表字段对应
            name属性:实体类属性名称
            column属性:生成表字段名称
        -->
        <property name="userName" column="username"></property>
        <property name="passWord" column="password"></property>
    </class>    
</hibernate-mapping>
4.创建hibernate的核心配置文件
- 位置名称固定:src下,hibernate.cfg.xml
- 引入dtd约束 <hibernate-core/orghibernate>

- hibernate操作过程中,只会加载核心配置文件 <所以要加载其他文件需要引入映射>
需要查找文件hibernate-release-5.0.12.Finalprojectetc下的
 <hibernate-configuration>
  <session-factory>
    <!-- 第一部分:配置数据库信息  必须的 -->
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql:///test_4</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">123456</property>
    <!-- 第二部分:配置hibernate信息  可选的 -->
    <!-- 输出底层sql语句 -->
    <property name="hibernate.show_sql">true</property>
    <!-- 输出底层sql语句格式 -->
    <property name="hibernate.format_sql">true</property>
    <!-- hibernate帮创建表,需要配置之后
        update:如果已经有表,更新,如果没有,创建
    -->
    <property name="hibernate.hbm2ddl.auto">update</property>
    <!-- 配置数据库方言     -->
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <!-- 第三部分:把映射文件放入核心配置文件中 必须的  -->
    <mapping resource="com/ants/entity/User.hbm.xml"></mapping>
  </session-factory>
</hibernate-configuration>
至此,hibernate的搭建完成

生活就要逢山开路遇水搭桥,愿共勉!
原文地址:https://www.cnblogs.com/TianMu/p/7840035.html