Hibernate : 环境搭建

第一步、创建工程,导入 jar 包。








第二步、创建实体类。


第三步、创建数据库表(hibernate 可自己创建一张表),并配置实体类和数据库表的一一对应关系。

使用配置文件。

1、创建一个 XML 格式的配置文件,名称、位置没有固定要求。建议在实体类所在的包里面进行创建(实体类名.hbm.xml),引入约束(dtd)。


配置实体类与表的映射关系。

<? xml version = "1.0" encoding = "UTF-8" ?>
<! DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
< hibernate-mapping >
       <!--1、配置类和表对应 
      class 标签 :
      name 属性 : 实体类全路径
      table 属性 : 数据库表名
      -->
       < class name = "com.ma.entity.user" table = "t_user" >
            
             <!-- 2、配置实体类 id 和表 id 对应
             hibernate 要求实体类有一个属性唯一值
             hibernate 要求表有字段作为唯一值
             -->
             <!-- id 标签:
            name 属性 : 实体类里面 id 属性
            column 属性 : 生成的表字段的名称 -->
            
             < id name = "uid" column = "uid" >
                   <!-- 设置数据库 id 增长策略
                  native : 主键自增长
                   -->
                   < generator class = "native" ></ generator >
             </ id >
             <!-- 配置其他属性 -->
             < property name = "username" column = "username" ></ property >
              < property name = "password" column = "password" ></ property >
               < property name = "address" column = "address" ></ property >
            
       </ class >
      
</ hibernate-mapping >

第四步、创建 hibernate 核心配置文件(名称( hibernate.cfg.xml)、位置固定(src下面))。

    1、配置数据库信息。

    2、配置 hibernate 信息。

    3、将映射文件加入核心配置文件中(hibernate 只加载这个主XML).
<? xml version = "1.0" encoding = "UTF-8" ?>
<! DOCTYPE hibernate-configuration PUBLIC
       "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
< hibernate-configuration >
       < session-factory >
       <!-- 1、配置数据库信息 -->
            
             < property name = "hibernate.connection.driver_class" > com.mysql.jdbc.Driver </ property >
            
             < property name = "hibernate.connection.url" > jdbc:mysql:///hibernate_day01 </ property >
            
             < property name = "hibernate.connection.username" > root </ property >
            
             < property name = "hibernate.connection.password" > 123456 </ property >
  
    <!-- 2、配置 hibernate 信息 (可选) -->
   
       <!-- 输出底层语句 -->
      
             < property name = "hibernate.show_sql" > true </ property >
      
             <!-- 对底层语句个格式化 -->
      
             < property name = "hibernate.format_sql" > true </ property >
      
       <!-- hibernate 自动创建表需要配置 -->
      
       < property name = "hibernate.hbm2ddl.auto" > update </ property >
      
       <!-- 配置数据库方言 -->
       < property name = "hibernate.dialect" > org.hibernate.dialect.MySQLDialect </ property >
   
    <!-- 3、将映射文件放置核心配置文件中( hibernate 只加载这个主XML) -->
             < mapping resource = "com/ma/entity/user.hbm.xml" ></ mapping >  
       </ session-factory >
</ hibernate-configuration >













猜你喜欢

转载自blog.csdn.net/young_1004/article/details/80580479