基于Hibernate实现CRUD(增删改查)

该博客演示了如何通过Hibernate框架在Java中创建实体类、映射文件,配置数据库连接,并实现用户数据的增删改查操作。主要涉及User类、hibernate.cfg.xml配置、Util工具类、DAO接口及其实现类。
摘要由CSDN通过智能技术生成

(此处略过创建项目的过程)

一、创建entity包,并在entity包里创建User类

package demo5.entity;

public class User {
    private int uId;
    private String uName;
    private String uPassword;
    private String uTel;

    public User(int uId, String uName, String uPassword, String uTel) {
        this.uId = uId;
        this.uName = uName;
        this.uPassword = uPassword;
        this.uTel = uTel;
    }



    public User() {

    }


    public int getuId() {
        return uId;
    }

    public void setuId(int uId) {
        this.uId = uId;
    }

    public String getuName() {
        return uName;
    }

    public void setuName(String uName) {
        this.uName = uName;
    }

    public String getuPassword() {
        return uPassword;
    }

    public void setuPassword(String uPassword) {
        this.uPassword = uPassword;
    }

    public String getuTel() {
        return uTel;
    }

    public void setuTel(String uTel) {
        this.uTel = uTel;
    }
}

二、user.hbm.xml

<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="demo5.entity.User" table="user">
        <id name="uId">
            <generator class="native"/>
        </id>
        <property name="uName"></property>
        <property name="uPassword" ></property>
        <property name="uTel" ></property>
    </class>
</hibernate-mapping>

三、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="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate?serverTimezone=Asia/Shanghai</property>
		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.connection.password">009474</property>
        <!--配置线程的上下文类型,保证一个线程只有一个session实例-->
		<property name="hibernate.current_session_context_class">thread</property>
		<property name="show_sql">true</property>
		<mapping resource="demo5/entity/user.hbm.xml"/>
	</session-factory>
</hibernate-configuration>

四、在entity里创建Util

package demo5.entity;

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

public class Util {
    private static Configuration cfg = null;
    private static SessionFactory sf = null;

    //在静态代码块里创建sessionFactory,只执行一次
    //实现sessionFactory的单态模式
    static
    {
        try {
            cfg = new Configuration().configure();
            sf = cfg.buildSessionFactory();
        } catch (HibernateException e) {
            e.printStackTrace();
        }
    }

    public static SessionFactory getSessionFactory()
    {
        return sf;
    }

    public void closeSessionFactory()
    {
        sf.close();
    }
}

五、创建dao包,并在dao包里创建userDao接口

package demo5.dao;

import demo5.entity.User;

public interface userDao {
    //添加
    public void add(User user);
    //查询
    public void findAllUser();
    //删除
    public void deleteUserById(int uId);
    //修改
    public void update(User user);
}

六、创建daoImpl包,并在daoImpl包里创建userDaoImpl

package demo5.daoImpl;

import demo5.dao.userDao;
import demo5.entity.User;
import demo5.entity.Util;
import org.hibernate.*;
import org.hibernate.query.Query;

import java.util.List;
import java.util.Scanner;

public class userDaoImpl implements userDao{

    /**
     * 查找全部用户
     */
    @Override
    public void findAllUser() {
        SessionFactory sf = null;
        Session session = null;
        Transaction ts = null;
        try {
            sf = Util.getSessionFactory();
            session = sf.getCurrentSession();
            ts = session.beginTransaction();
            Query query = session.createQuery("from User");
            List<User> users = query.list();
            //使用forEach遍历集合
            for (User user1 : users) {
                System.out.println(user1.getuId());
                System.out.println(user1.getuName());
                System.out.println(user1.getuPassword());
                System.out.println(user1.getuTel());
            }
            ts.commit();
        } catch (HibernateException e) {
            if(ts != null)
            {
                ts.rollback();
            }
            e.printStackTrace();
        }
    }

    /**
     * 根据id删除用户
     * @param uId
     */
    @Override
    public void deleteUserById(int uId) {
        Scanner scanner = new Scanner(System.in);
        SessionFactory sf = null;
        Session session = null;
        Transaction ts = null;
        User user = new User();
        try {
            sf = Util.getSessionFactory();
            session = sf.getCurrentSession();
            ts = session.beginTransaction();
            User p = (User) session.get(User.class, uId);
            session.delete(p);


            ts.commit();
        } catch (HibernateException e) {
            if(ts != null)
            {
                ts.rollback();
            }
            e.printStackTrace();
        }
    }

    /**
     * 修改用户信息
     * @param user
     */
    @Override
    public void update(User user) {
        SessionFactory sf = null;
        Session session = null;
        Transaction ts = null;
        try {
            sf = Util.getSessionFactory();
            session = sf.getCurrentSession();
            ts = session.beginTransaction();
            session.update(user);
            ts.commit();
        } catch (HibernateException e) {
            if(ts != null)
            {
                ts.rollback();
            }
            e.printStackTrace();
        }
    }

    /**
     * 添加用户
     * @param user
     */
    @Override
    public void add(User user) {
        SessionFactory sf = null;
        Session session = null;
        Transaction ts = null;
        System.out.println("添加用户");
        try {
            sf = Util.getSessionFactory();
            session = sf.getCurrentSession();
            ts = session.beginTransaction();
            session.save(user);
            System.out.println(user.toString());
            ts.commit();
        } catch (HibernateException e) {
            if(ts != null)
            {
                ts.rollback();
            }
            e.printStackTrace();
        }
   }
}

七、创建test包,并在test包里创建userTest类

package demo5.test;

import demo5.daoImpl.userDaoImpl;
import demo5.entity.User;
import org.junit.Test;

public class userTest {
    userDaoImpl uImpl = new userDaoImpl();

    @Test
    public void testAdd(){
        User user = new User(2, "bjhbx","665544", "18844629999");
        uImpl.add(user);
    }

    @Test
    public void testFind() {
        User user=new User();
        uImpl.findAllUser();
    }

    @Test
    public void testDelete() {
        uImpl.deleteUserById(2);
    }

    @Test
    public void testUpdate() {
        User user=new User(1,"luyd","332211","18845622364");
        uImpl.update(user);
    }
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值