hibernate之初学增删改查

Posted 情似雨餘黏地絮

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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>

 

以上是关于hibernate之初学增删改查的主要内容,如果未能解决你的问题,请参考以下文章

Hibernate之API初识及增删改查实现

Struts2+Spring+Hibernate实现员工管理增删改查功能之ssh框架整合

hibernate关联对象的增删改查------增

Hibernate ORM框架——续第一章:Hibernate的增删改查(第一个hibernate代码的优化)

Hibernate入门案例及增删改查

拯救初学者之开发项目如何正确运用ArrayList,while实现项目的循环和数据增删改查