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>
时间: 2024-08-28 23:40:41

hibernate之初学增删改查的相关文章

Rhythmk 学习 Hibernate 01 - maven 创建Hibernate 项目之 增删改查入门

1.环境: Maven :3.1.1 开发工具:Spring Tool Suite 数据库 : Mysql  5.6 2.项目文件结构 文件代码: 2.1 .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.ap

肝 hibernate 配置and增删改查 and 测试

已经通宵三天撸代码了,现在的我已经养成晚上修仙写代码的节奏了.....最近 刚刚复习到了 hibernate 谈谈 这篇文章就谈谈我对这货的理解吧. 在看这篇文章之前希望你 知道sessionfactory 和session 还有 transaction(事物) 诶嘿不造的可以去看看http://blog.csdn.net/u012377333/article/details/48086193  OK正题开始 步骤 我们需要一个可以持久化的bean类 还有它的附属映射 hbm.xml文件 以及d

Hibernate入门_增删改查

一.Hibernate入门案例剖析:  ①创建实体类Student 并重写toString方法 public class Student { private Integer sid; private Integer age; private String name; public Integer getSid() { return sid; } public void setSid(Integer sid) { this.sid = sid; } public Integer getAge()

Hibernate下的增删改查

概述: 关系--对象映射的中间件,属于开源ORM框架,是我们业务逻辑层中的调用数据库的中间件 演变: jdbc---hibernater---mybatis hibernate和mybatis区别? 1:hiberanter学习的难度要比mybatis要大,复杂度要高 2:hibernate不需要写sql语句,自动生成,而mybatis需要写sql语句进行数据操作 3:hibernate支持分页(API),而mybatis不支持分页(那是属于插件) 4:hibernate支持事务处理,而myba

Hibernate学习-------数据库增删改查操作(部分)

(1)增加和删除 <span style="white-space:pre"> </span>@Test public void test() { EStudent student=new EStudent(); student.setName("张三"); student.setSex("男"); Session session=sf.openSession(); session.beginTransaction();

struts+hibernate 请求数据库增删改查(小项目实例)

  StudentAction.java package com.action; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts2.ServletActionCont

5.Hibernate实现全套增删改查和ajax异步分页

1.1 创建如下oracle数据库脚本 1 drop sequence seq_stu; 2 3 create sequence SEQ_STU 4 minvalue 1 5 maxvalue 999999999999999999999999999 6 start with 1 7 increment by 1 8 cache 20; 9 10 drop table student; 11 12 create table STUDENT 13 ( 14 sid NUMBER not null,

Hibernate的入门(增删改查):

注意:本次的记录是在上一篇Hibernate入门的基础上应用的 1.目录 2.实体类修改 1 package com.itheima.domain; 2 3 /* 4 * 客户的javaBean 5 * @author chenyanlong 6 */ 7 public class Customer { 8 private Long cust_id; 9 private String cust_name; 10 private Long cust_user_id; 11 private Long

Hibernate 基本增删改查操作

本文将要介绍Hibernate基本的增删改查的操作的实现,首先我们创建一个对象实例.一般情况下会创建User,本例也不例外需要创建这样的对象. [转载使用,请注明出处:http://blog.csdn.net/mahoking] User对象 public class User { private Integer id; private String userName; private String password; /*以下省略getter与setter*/ } 配置User.hbm.xml