码迷,mamicode.com
首页 > 编程语言 > 详细

java之hibernate之crud

时间:2019-07-16 23:59:56      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:cti   www   stand   create   poj   inf   需要   nat   ble   

这篇文章主要讲解:

  1>.对Hibernate使用的一些简单封装;

·  2>.在单元测试中,使用Hibernate的封装的工具进行增删改查的测试

1.目录结构展示

技术图片

2.代码展示

2.0 配置文件 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>
        <!-- 默认 localhost:3306 -->
        <property name="connection.url">jdbc:mysql:///test</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>
        
        <!-- 通用配置 -->
        <!-- 方言:hibernate要支持多种数据库,根据不同数据库生成对应的sql语句
            告诉hibernate使用的什么数据库,以便生成对应数据库的sql
         -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <!-- 打印sql语句 -->
        <property name="show_sql">true</property>
        <!-- 格式化sql -->
        <property name="format_sql">true</property>
        <!-- 映射信息  注意映射文件存放的是文档路径 需要用/ -->
        <mapping resource="cn/vincent/pojo/User.hbm.xml"/>
    </session-factory>
</hibernate-configuration>
View Code

2.1 pojo 类 

User

技术图片
package cn.vincent.pojo;

import java.io.Serializable;

public class User implements Serializable {
    private int  id;
    private String name;
    private int age;
    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 int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + age;
        result = prime * result + id;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        User other = (User) obj;
        if (age != other.age)
            return false;
        if (id != other.id)
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }
    
}
View Code

User.hbm.xml 即User的映射

技术图片
<?xml version="1.0" encoding="UTF-8"?>
<!-- 映射文件的头文件和hibernate.cfg.xml的头文件不一样 -->
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="cn.vincent.pojo">
    
    <class name="User" table="t_user">
        
        <id name="id" column="id" type="int">
            
            <generator class="native"></generator>
        </id>
        
        <property name="name" column="name" type="java.lang.String"/>
        <property name="age" column="age" type="int"/>
    </class>
</hibernate-mapping>
View Code

2.2 util 工具类

package cn.vincent.util;

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

public class HibernateUtil {
    private static Configuration cfg;
    private static ServiceRegistry registry;
    private static SessionFactory factory;
    private static ThreadLocal<Session> session;
    
    static{
        //初始化
        cfg=new Configuration().configure();
        registry=new StandardServiceRegistryBuilder()
                    .applySettings(cfg.getProperties())
                    .build();
        factory=cfg.buildSessionFactory(registry);
        session=new ThreadLocal<>();
    }
    //获取连接
    public static Session getSession(){
        if(session.get()==null){
            session.set(factory.openSession());
        }
        return session.get();
    }
    
    //释放资源
    public static void close(){
        if(session.get()!=null){
            session.get().close();
            session.set(null);
        }
    }
    
}

2.3 单元测试

HibernateTest

package cn.vincent.hibernate;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

import cn.vincent.pojo.User;
import cn.vincent.util.HibernateUtil;

public class HibernateTest {

    //根据id查询单个对象
        @Test
        public void testGetById(){
            Session session = HibernateUtil.getSession();
            User user=(User)session.get(User.class, 2);
            System.out.println(user.getId()+"----"+user.getName()+"----"+user.getAge());
            HibernateUtil.close();
        }
        //添加数据
        @Test
        public void testSave(){
            Session session=null;
            Transaction tx =null;
            try {
                session = HibernateUtil.getSession();
                User user= new User();
                user.setName("金庸");
                user.setAge(80);
                //开启事务
                tx = session.beginTransaction();
                //返回 被保存数据的id
                session.save(user);
                //提交事务
                tx.commit();
                System.out.println("保存数据成功");
            } catch (Exception e) {
                e.printStackTrace();
                //回滚事务
                if(tx!=null)
                    tx.rollback();
                System.out.println("保存数据失败");
            }finally{
                HibernateUtil.close();
            }
            
        }
        //删除数据
        @Test
        public void testDelete(){
            Session session=null;
            Transaction tx =null;
            try {
                session = HibernateUtil.getSession();
                //开启事务
                tx = session.beginTransaction();
                User user =(User)session.get(User.class, 4);
                session.delete(user);
                //提交事务
                tx.commit();
                System.out.println("删除数据成功");
            } catch (Exception e) {
                e.printStackTrace();
                //回滚事务
                if(tx!=null)
                    tx.rollback();
                System.out.println("删除数据失败");
            }finally{
                HibernateUtil.close();
            }
        }
        //更新
        @Test
        public void testUpdate(){
            Session session=null;
            Transaction tx =null;
            try {
                session = HibernateUtil.getSession();
                //开启事务
                tx = session.beginTransaction();
                User user =(User)session.get(User.class, 4);
                user.setName("本拉登");
                session.update(user);
                //提交事务
                tx.commit();
                System.out.println("更新数据成功");
            } catch (Exception e) {
                e.printStackTrace();
                //回滚事务
                if(tx!=null)
                    tx.rollback();
                System.out.println("更新数据失败");
            }finally{
                HibernateUtil.close();
            }
        }
        //查询所有
        @Test
        public void testFindAll(){
            Session session=null;
            try {
                session = HibernateUtil.getSession();
                List<User> list = session.createCriteria(User.class).list();
                for(User u:list){
                    System.out.println(u);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally{
                HibernateUtil.close();
            }
        }
}

3.单元测试运行效果

运行单元测试

技术图片

如下图:

技术图片

 

java之hibernate之crud

标签:cti   www   stand   create   poj   inf   需要   nat   ble   

原文地址:https://www.cnblogs.com/Vincent-yuan/p/11198327.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!