Hibernate learning ------- database addition, deletion, modification, and query operations (Part)
(1) add and delete
@ Testpublic void test () {EStudent student = new EStudent (); student. setName ("Zhang San"); student. setSex ("male"); Session session = sf. openSession (); session. beginTransaction (); session. save (student); // Add // delete operation delete EStudent s = new EStudent (); s. setId (4); // sets the ID session. delete (s); session. getTransaction (). commit (); session. close ();}
(2) get and Load queries. Pay attention to the two differences.
@ Testpublic void testLoad () // Load read database {Session session = sf. openSession (); session. beginTransaction (); // The parameters are the EStudent object class and the primary key to be queried. // Load is only used when the object to be queried (such as getName) the agent object EStudent s = (EStudent) session is returned. load (EStudent. class, 1); System. out. println (s. getId () + "--" + s. getName (); session. getTransaction (). commit (); // System. out. println (s. getId () + "--" + s. getName (); // if the property method of the queried object is used only here, the session is reported incorrectly. close () ;}@ Testpublic void testGet () // get read database {Session session = sf. openSession (); session. beginTransaction (); // The parameters are the EStudent object class and the primary key to be queried. // generate and execute the SQL statement EStudent s = (EStudent) session immediately. get (EStudent. class, 1); System. out. println (s. getId () + "--" + s. getName (); session. getTransaction (). commit (); session. close ();}
(3) update operations
@ Testpublic void testUpdate () // update database {Session session = sf. openSession (); session. beginTransaction (); // first query and then modify, if the modified attribute is the same as the original one, no updates will be made. // The parameters are the EStudent object class and the primary key to be queried. // generate and execute the SQL statement EStudent s = (EStudent) session. get (EStudent. class, 1); s. setName ("dou bean 1"); session. update (s); // create a new object, set the ID, and modify it. If no ID is set, an error occurs. // if only some attributes are set, the unspecified attribute is null or the default value is EStudent s2 = new EStudent (); s2.setId (6); // The database exists, if the specified ID does not exist in the Database, s2.setName (""); session. update (s2); session. getTransaction (). commit (); session. close ();}
(4) HQL update operation
@ Testpublic void testUpdateHQL () // update the database using HQL {Session session = sf. openSession (); session. beginTransaction (); // org. hibernate. query Note: The Update object Query q = session. createSQLQuery ("Update newtablestudent set name = 'zhang san' where name = 'doudou doube'" );q.exe cuteUpdate (); // Update the session. getTransaction (). commit (); session. close ();}