Hibernate3 adds, deletes, and changes data

The following operations are completed in the Junit test:
1. Create a new tool class to obtain SessionFactory and session, sample code:

package com.gx.util;

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

public class HibernateSessionFactory {
    
    
   
	private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private static org.hibernate.SessionFactory sessionFactory;
	
    private static Configuration configuration = new Configuration();
    private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
    private static String configFile = CONFIG_FILE_LOCATION;

	static {
    
    
    	try {
    
    
			configuration.configure(configFile);
			sessionFactory = configuration.buildSessionFactory();
		} catch (Exception e) {
    
    
			System.err.println("%%%% Error Creating SessionFactory %%%%");
			e.printStackTrace();
		}
    }
    private HibernateSessionFactory() {
    
    
    }
	
    public static Session getSession() throws HibernateException {
    
    
        Session session = (Session) threadLocal.get();

		if (session == null || !session.isOpen()) {
    
    
			if (sessionFactory == null) {
    
    
				rebuildSessionFactory();
			}
			session = (sessionFactory != null) ? sessionFactory.openSession()
					: null;
			threadLocal.set(session);
		}

        return session;
    }

	public static void rebuildSessionFactory() {
    
    
		try {
    
    
			configuration.configure(configFile);
			sessionFactory = configuration.buildSessionFactory();
		} catch (Exception e) {
    
    
			System.err.println("%%%% Error Creating SessionFactory %%%%");
			e.printStackTrace();
		}
	}

    public static void closeSession() throws HibernateException {
    
    
        Session session = (Session) threadLocal.get();
        threadLocal.set(null);

        if (session != null) {
    
    
            session.close();
        }
    }

	public static org.hibernate.SessionFactory getSessionFactory() {
    
    
		return sessionFactory;
	}

	public static void setConfigFile(String configFile) {
    
    
		HibernateSessionFactory.configFile = configFile;
		sessionFactory = null;
	}

	public static Configuration getConfiguration() {
    
    
		return configuration;
	}
}

2. Add data in Hibernate, sample code:

/*新增一定要开启事务*/
@Test
public void testInsert() throws ParseException{
    
    
	//1获取session
	Session session=HibernateSessionFactory.getSession();
	//2获取事务
	Transaction transaction=session.getTransaction();
	//3开启事务
	transaction.begin();
	
	User user=new  User();
	user.setUsername("testInsert");
	user.setPassword("123");
	user.setSex(true);
	user.setCreatetime(new Date());
	user.setPowerid(1);
	
	session.save(user);
	//提交事务
	transaction.commit();
	//关闭session
	session.close();
}

Screenshot of running result:
Insert picture description here

2. Modify the data
Hibernate modifies the data in 3 steps. Firstly, query the data that needs to be modified, then update the data, and finally save the modified data to the database. Sample code:

/*修改需要开启事务*/
@Test
public void testUpdate(){
    
    
	//1获取session
	Session session=HibernateSessionFactory.getSession();
	//2获取事务
	Transaction transaction=session.getTransaction();
	//3开启事务
	transaction.begin();
	
	//查询需要修改的数据
	User user=(User) session.get(User.class, 39);
       //修改数据
	user.setUsername("testUpdate");
	
	//把修改后的数据保存到数据库
	session.update(user);
	transaction.commit();
	//关闭session
	session.close();
}

Screenshot of running result:

Insert picture description here

3. Delete data
There are two steps to delete data in Hibernate. First, query the data that needs to be modified, and then delete the data. Sample code:

/*删除需要开启事务*/
@Test
public void testDelete(){
    
    
	//1获取session
	Session session=HibernateSessionFactory.getSession();
	//2获取事务
	Transaction transaction=session.getTransaction();
	//3开启事务
	transaction.begin();
	
	//查询需要删除的数据
	User user=(User) session.get(User.class, 39);
	
	//删除数据
	session.delete(user);
	
	transaction.commit();
	session.close();
}

Screenshot of the running result, the data with id 39 has been deleted:
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_44547592/article/details/108460553