Second, because you want to test the content of the output query, you need to Override the full-parameter toString() method in the
persistent class. That's all for the changes in the persistent class.
package hiber1; public class User { private int uid; private String username; private String password; private String address; public int getUid() { return uid; } public void setUid(int uid) { this.uid = uid; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "User [uid=" + uid + ", username=" + username + ", password=" + password + ", address=" + address + "]"; } }
Second, create a new test class, this class needs to get the session from the factory class
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 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(); } }
The rest of the content will not be pasted. Remember to clearly write the name of the data table to be obtained in the xml mapping file.
Finally , the output content is as follows: