利用maven搭建一个简单的hibernate示例

利用maven搭建hibernate实例
1、项目结构:
这里写图片描述
2、配置pom.xml文件

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.lyc.test</groupId>
  <artifactId>helloWorld</artifactId>
  <version>0.0.1-SNAPSHOT</version>

    <properties>
        <!-- hibernate版本号 -->
        <hibernate.version>5.1.5.Final</hibernate.version>
    </properties>
  <dependencies>
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>4.8.2</version>
          <scope>test</scope>
        </dependency>
          <!-- mysql驱动包 -->
        <dependency>
           <groupId>mysql</groupId>
           <artifactId>mysql-connector-java</artifactId>
           <version>5.1.29</version>
        </dependency>
        <!-- hibernate核心jar包 -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <!-- hibernate注解 -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-annotations</artifactId>
            <version>3.5.0-Final</version>
        </dependency>
        <!-- Javassist是一款字节码编辑工具 -->
        <dependency>
            <groupId>org.javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>3.21.0-GA</version>
        </dependency>
        <!-- Antlr 是一个基于 Java 开发的功能强大的语言识别工具 -->
        <dependency>
            <groupId>antlr</groupId>
            <artifactId>antlr</artifactId>
            <version>2.7.6</version>
        </dependency>
        <!-- commons-collections 为Java标准的Collections API提供了相当好的补充 -->
        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.2.2</version>
        </dependency>
        <!-- dom4j是一个Java的XML API -->
        <dependency>
            <groupId>dom4j</groupId>
            <artifactId>dom4j</artifactId>
            <version>1.6.1</version>
        </dependency>
        <!-- 
            1、ORM映射元数据
            2、JPA 的API
                用来操作实体对象,执行CRUD操作,框架在后台替我们完成所有的事情,开发者从繁琐的JDBC和SQL代码中解
                脱出来。
            3、查询语言 
        -->
        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.0-api</artifactId>
            <version>1.0.0.Final</version>
        </dependency>
  </dependencies>
    <build>
        <finalName>maven-hibernate-demo</finalName>
    </build>
</project>

3、编辑hibernate配置文件hibernate.cfg.xml

<!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>
    <!-- 配置数据库连接信息 -->
    <!-- 数据库驱动 -->
    <property name="connection.driver_class">
        com.mysql.jdbc.Driver
    </property>
    <!-- url 相当于:jdbc:mysql://localhost:3306/hibernate?useUnicode=true&characterEncoding=UTF-8-->
    <property name="connection.url">
        <!-- jdbc:mysql:///hibernate?useUnicode=true&characterEncoding=UTF-8这样写有问题 -->
        <![CDATA[jdbc:mysql://localhost:3306/hibernate?useUnicode=true&characterEncoding=utf8]]>
    </property>
    <property name="connection.username">root</property>
    <property name="connection.password">root</property>
    <!-- hibernate可选项信息 -->
    <!-- 数据库方言 -->
    <property name="dialect">
        org.hibernate.dialect.MySQL5Dialect
    </property>
    <!-- 是否打印sql语句 -->
    <property name="show_sql">true</property>
    <!-- 格式化sql语句 -->
    <property name="format_sql">true</property>
    <!-- 数据库更新方式:
        create:每次执行 都先把原有数据表删除,然后创建该表
        create-drop:使用 create-drop时,在显式关闭SessionFactory时,
        将drop掉数据库schema(表). 
        validate:检测
        update:如果表不存在 则创建,有就不用创建
     -->
    <property name="hbm2ddl.auto">update</property>
    <!-- 映射文件信息 -->
    <mapping resource="com/lyc/pojo/User.hbm.xml" />
</session-factory>
</hibernate-configuration>

4、创建实体类User

package com.lyc.pojo;

public class User {
    private int id;
    private String name;
    private String pwd;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPwd() {
        return pwd;
    }
    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
    @Override
    public String toString() {
        return this.id+this.name+this.pwd;
    }
}

并编辑对应的映射文件User.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
    <!-- package声明pojo类所在的包,如果不写 那么在class中需要指明pojo类所在的包
         schema指数据库模式 一个模式下可以有多张表
     -->
<hibernate-mapping package="com.lyc.pojo" >
    <!-- class指映射一个pojo类
        提供了公共的无参构造方法-通过反射产生对象
        属性用private修饰,并且生成对应的get/set方法
        类不能用final来修饰-hibernate会产生代理类(cglib)
        类需要指明标识
        name表示pojo类名
        table表示pojo类对应数据库中的表名;如果不写默认是类名
     -->
    <class name="User" table="user">
        <!-- 
            id表示实体类的标识(OID)
            对应数据库表中的主键
            name指实体类的标识属性名
            column表示对应数据库表的列名:如果不写 则数据库表中列名和属性名一致
            length表示数据库表中 对应数据类型的长度 ,如果不写有默认长度
            type表示类型如果不写hibernate可以找到对应pojo类的属性的类型
         -->
        <id name="id" column="id">
            <!-- 主键生成策略
                increment 用于为long, short或者int类型生成 唯一标识。
                只有在没有其他进程往同一张表中插入数据时才能使用。 在集群下不要使用
                (mysql,ms sql)
                identity 对DB2,MySQL, MS SQL Server, Sybase和HypersonicSQL
                的内置标识字段提供支持。 返回的标识符是long, short 或者int类型的。 
                sequence 在支持序列的数据库中使用 oracle
                <generator class="sequence">
                    <param name="sequence">user_seq</param>
                </generator>
                uuid UUID被编码为一个32位16进制数字的字符串。 
                native 根据底层数据库的能力选择identity, sequence 或者hilo中的一个。
                assigned 自己指定主键
             -->
            <generator class="native"/>
        </id>
        <!-- 实体类的属性 
            name:指明 pojo类属性名称(区分大小写)
        -->
        <property name="name">
            <column name="name"></column>
        </property> 
        <property name="pwd"/>  
    </class>
</hibernate-mapping>

5、编写测试类

package com.lyc.hibernate;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.junit.Test;

import com.lyc.pojo.User;

public class HibernateTest {
    @Test
    public void testHibernate(){
        Configuration cfg = null;
        SessionFactory sf = null;
        Session session = null;
        Transaction tx = null;
        try{
            cfg = new Configuration().configure();
            ServiceRegistry registry = new StandardServiceRegistryBuilder().configure().build();
            sf = cfg.buildSessionFactory(registry);
            session = sf.openSession();
            tx = session.beginTransaction();
            User user = new User();
            user.setName("咪咪");
            user.setPwd("1111");
            session.save(user); 
            //6.提交事务
            tx.commit();
        }catch (Exception e) {
            e.printStackTrace();
            //回滚事务
            tx.rollback();
            throw new HibernateException(e.getCause());

        }finally{
            //7.关闭session
            if(session!=null&&session.isOpen())
            session.close();
            sf.close();
        }
    }

}

至此利用maven搭建好了一个hibernate项目
运行结果:
这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值