当前位置: 首页 > news >正文

hibernate之初学增删改查

  项目搭建啥的看我的上一篇文章,我就不多逼逼了,接下来就贴代码了

工具类:

package com.xinzhi.utils;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
    public static SessionFactory sf;
    static {
        sf = new Configuration().configure().buildSessionFactory();
    }

    public static Session getSession() {
        return sf.openSession();
    }

}

  对象序列化是为了反序列化用的,比如将一个对象写入到文件,或者作为流的形式传给第三方,那么这个类必须实现Serializable接口,并且定义一个私有的常量SerializableID,不然就不能从文件中读取对象了,接收方也没法还原这个对象

  实际上就是一个ID用到了

package com.xinzhi.dao;

import java.io.Serializable;
import java.util.List;

import com.xinzhi.entity.UserEntity;

public interface UserDao {
    // 增加一个用户
    public void saveUser(UserEntity userEntity);

    // 删除一个用户
    public void deleteUser(Serializable id);

    // 修改一个用户
    public void updateUser(UserEntity userEntity);

    // 查询所有的用户
    public List<UserEntity> selectUser();

    // 查询指定用户
    public UserEntity selectOneUser(Serializable id);

    // 分页查询
    public List<UserEntity> pageSelectUser(int currentPage, int pageCount);
}

 接下就是上面方法的代码实现:

package com.xinzhi.dao.impl;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.xinzhi.dao.UserDao;
import com.xinzhi.entity.UserEntity;
import com.xinzhi.utils.HibernateUtil;

public class UserDaoImpl implements UserDao {

    @Override
    public void deleteUser(Serializable id) {
        Session session = null;
        Transaction beginTransaction = null;
        try {
            session = HibernateUtil.getSession();
            beginTransaction = session.beginTransaction();
            Object object = session.get(UserEntity.class, id);
            if (object != null) {
                session.delete(object);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            beginTransaction.commit();
            session.close();
        }

    }

    @Override
    public List<UserEntity> pageSelectUser(int currentPage, int pageCount) {
        Session session = null;
        Transaction beginTransaction = null;
        List<UserEntity> list = null;
        try {
            session = HibernateUtil.getSession();
            beginTransaction = session.beginTransaction();
            Query createQuery = session.createQuery("from UserEntity");
            createQuery.setFirstResult(currentPage);
            createQuery.setMaxResults(pageCount);
            list = createQuery.list();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            beginTransaction.commit();
            session.close();
            return list;
        }
    }

    @Override
    public void saveUser(UserEntity userEntity) {
        Session session = null;
        Transaction beginTransaction = null;
        try {
            session = HibernateUtil.getSession();
            beginTransaction = session.beginTransaction();
            session.saveOrUpdate(userEntity);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            beginTransaction.commit();
            session.close();
        }
    }

    @Override
    public UserEntity selectOneUser(Serializable id) {
        Session session = null;
        Transaction beginTransaction = null;
        UserEntity userEntity = null;
        try {
            session = HibernateUtil.getSession();
            beginTransaction = session.beginTransaction();
            userEntity = (UserEntity) session.get(UserEntity.class, id);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            beginTransaction.commit();
            session.close();
            return userEntity;
        }
    }

    @Override
    public List<UserEntity> selectUser() {
        Session session = null;
        Transaction transaction = null;
        List<UserEntity> list = null;
        try {
            session = HibernateUtil.getSession();
            transaction = session.beginTransaction();
            Query query = session.createQuery("from UserEntity ");
            list = query.list();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            transaction.commit();
            session.close();
            return list;
        }
    }

    @Override
    public void updateUser(UserEntity userEntity) {
        Session session = null;
        Transaction beginTransaction = null;
        try {
            session = HibernateUtil.getSession();
            beginTransaction = session.beginTransaction();
            session.update(userEntity);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            beginTransaction.commit();
            session.close();
        }
    }

}

  接下来是User的实体类

package com.xinzhi.entity;


public class UserEntity {
    private int id;
    private String username;
    private String pwd;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    @Override
    public String toString() {
        return "UserEntity [id=" + id + ", pwd=" + pwd + ", username="
                + username + "]";
    }

}

  接下来是对impl中的所有方法进行测试:

package com.xinzhi.test;

import java.util.List;

import org.junit.Test;

import com.xinzhi.dao.impl.UserDaoImpl;
import com.xinzhi.entity.UserEntity;

public class TestUser {
    @Test
    public void testDelete() throws Exception {
        UserDaoImpl userDaoImpl = new UserDaoImpl();
        userDaoImpl.deleteUser(2);
    }

    @Test
    public void testSelectAll() throws Exception {
        UserDaoImpl userDaoImpl = new UserDaoImpl();
        List<UserEntity> selectUser = userDaoImpl.selectUser();
        System.out.println(selectUser);
    }

    @Test
    public void testSelectLimit() throws Exception {
        UserDaoImpl userDaoImpl = new UserDaoImpl();
        List<UserEntity> selectUser = userDaoImpl.pageSelectUser(0, 3);
        System.out.println(selectUser);
    }

    @Test
    public void testSelectOneUser() throws Exception {
        UserDaoImpl userDaoImpl = new UserDaoImpl();
        UserEntity selectOneUser = userDaoImpl.selectOneUser(3);
        System.out.println(selectOneUser);
    }

    @Test
    public void testUpdateUser() throws Exception {
        UserDaoImpl userDaoImpl = new UserDaoImpl();
        UserEntity userEntity = new UserEntity();
        userEntity.setId(10);
        userEntity.setPwd("2113");
        userEntity.setUsername("shaoxin");
        userDaoImpl.updateUser(userEntity);
        System.out.println(userDaoImpl.selectOneUser(10));
    }

    @Test
    public void testSaveUser() throws Exception {
        UserDaoImpl userDaoImpl = new UserDaoImpl();
        UserEntity userEntity = new UserEntity();
        userEntity.setUsername("shaoxin");
        userEntity.setPwd("2113");
        userDaoImpl.saveUser(userEntity);
        System.out.println(userDaoImpl.selectOneUser(11));
    }
}

接下来是文件配置文件名固定用UserEntity.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">

<hibernate-mapping 
    package="com.xinzhi.entity">
    
    <class name="UserEntity"  table="user"><!--
        这里是主键,name是你实体类中的主键名称 , column是你数据库中字段的主键
        --><id name="id" column="id">
            <generator class="native"/>
        </id><!--
        下面的分别是实体类中的属性对应数据库中的字段
        --><property name="username" column="username"></property>
        <property name="pwd" column="pwd"></property>
    </class>

</hibernate-mapping>

接下来是Hibernate的配置文件:

<!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="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">123456</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/webproject</property><!--
                反正下面这段话我直接跑去hibernate.dialect包下复制文件路径的时候gg了要指定特定的方言
        --><property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
        <property name="hibernate.show_sql">true</property>
        <property name=""></property>
        <!--
                如果不加下面这句话,引入你自己写的配置文件,你将会很绝望
        --><mapping resource="com/xinzhi/entity/UserEntity.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

 

转载于:https://www.cnblogs.com/ShaoXin/p/7090254.html

相关文章:

  • Android之使用传感器获取相应数据
  • css实现文字两端对齐
  • jQuery高性能自己定义滚动栏美化插件
  • Visual Code中的智能提示
  • 什么是ODBC ?
  • Perfect or Good Enough – 关于测试程度的一些探讨
  • 得到存储过程中最后拼接出来的语句
  • python 同时打开两个文件以及打开文件的基本操作
  • open_basedir restriction in effect,解决php引入文件权限问题
  • Android应用完全退出的几种方法
  • 【AHOI2005】病毒检测
  • 数据挖掘 - 算法 - ID3 - 转自 http://www.cnblogs.com/dztgc/archive/2013/04/22/3036529.html
  • asp.net MVC html.ActionLink的几种参数格式
  • jquery获取元素各种宽高及页面宽高总结
  • c# AOP 文章地址
  • [译] React v16.8: 含有Hooks的版本
  • 「译」Node.js Streams 基础
  • 【162天】黑马程序员27天视频学习笔记【Day02-上】
  • css属性的继承、初识值、计算值、当前值、应用值
  • EOS是什么
  • Github访问慢解决办法
  • HashMap剖析之内部结构
  • java第三方包学习之lombok
  • java概述
  • JS题目及答案整理
  • open-falcon 开发笔记(一):从零开始搭建虚拟服务器和监测环境
  • 规范化安全开发 KOA 手脚架
  • 融云开发漫谈:你是否了解Go语言并发编程的第一要义?
  • 如何用vue打造一个移动端音乐播放器
  • 说说动画卡顿的解决方案
  • 算法之不定期更新(一)(2018-04-12)
  • 详解NodeJs流之一
  • 小程序01:wepy框架整合iview webapp UI
  • 一个项目push到多个远程Git仓库
  • 在GitHub多个账号上使用不同的SSH的配置方法
  • 在Mac OS X上安装 Ruby运行环境
  • k8s使用glusterfs实现动态持久化存储
  • Nginx实现动静分离
  • 阿里云移动端播放器高级功能介绍
  • ​如何防止网络攻击?
  • #define
  • #gStore-weekly | gStore最新版本1.0之三角形计数函数的使用
  • (173)FPGA约束:单周期时序分析或默认时序分析
  • (AtCoder Beginner Contest 340) -- F - S = 1 -- 题解
  • (ZT)北大教授朱青生给学生的一封信:大学,更是一个科学的保证
  • (附源码)apringboot计算机专业大学生就业指南 毕业设计061355
  • (附源码)springboot车辆管理系统 毕业设计 031034
  • (学习日记)2024.03.12:UCOSIII第十四节:时基列表
  • (转)h264中avc和flv数据的解析
  • .bat批处理(十):从路径字符串中截取盘符、文件名、后缀名等信息
  • .NET单元测试
  • .NET多线程执行函数
  • .NET命名规范和开发约定
  • .NET中的Event与Delegates,从Publisher到Subscriber的衔接!
  • ??如何把JavaScript脚本中的参数传到java代码段中