(Modified) Use session's update() method to modify information from the database

As with the basic query process, the source code is given below:
package hiber1;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.jupiter.api.Test;

public class HiberGet {
	@Test
	public void testUpdate(){
		//1. Call the tool class (the factory class of the session) and get the sessionfactory
				SessionFactory sessionF = HiberTool.getSessionFactory();
				//2. Get session
				Session session = sessionF.openSession();
				//3. Open the transaction
				Transaction tx = session.beginTransaction();
				
				//4. Modify operation (key point), the principle to follow is: first obtain, then modify
				User user = session.get(User.class, 2);//先获取
				user.setUsername("Eastern Invincible");//Modify again
				session.update(user);//Final submission
				
				//5. Commit the transaction
				tx.commit();
				//6. Close
				session.close();
				sessionF.close();
	}
	
	
	@Test
	public void testGet(){
		//1. Call the tool class (the factory class of the session) and get the sessionfactory
		SessionFactory sessionF = HiberTool.getSessionFactory();
		//2. Get session
		Session session = sessionF.openSession();
		//3. Open the transaction
		Transaction tx = session.beginTransaction();
		//4. According to the id query, get the User object (emphasis)
		User user = session.get(User.class, 2);//The first parameter: entity class.class||The second parameter: id value
		System.out.println(user);//Direct output of user remember to rewrite toString in User class
		//5. Commit the transaction
		tx.commit();
		//6. Close
		session.close();
		sessionF.close();
	}

}










Again: the process is almost the same.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326048561&siteId=291194637