Hibernate CRUD Operations
Next, we will introduce how Hibernate implements CRUD operations on the database.
insert record
Hibernate provides us with a save() method in the Session interface, which can insert records into the database table.
1. In the test class MyTest, create a method named testInsert with the following code.
/** * save data */ @Test public void testInsert() { //Load Hibernate core configuration file Configuration configuration = new Configuration().configure(); //Create a SessionFactory to get the Session connection object SessionFactory sessionFactory = configuration.buildSessionFactory(); //Get the session connection object Session session = sessionFactory.openSession(); // start transaction Transaction transaction = session.beginTransaction(); //create entity class object User user = new User(); user.setUserId("003"); user.setUserName("new user"); user.setPassword("654321"); user.setEmail("14234567@test.com"); //Insert data into the user table, the return value is the primary key id of the newly added data Serializable save = session.save(user); System.out.println("Primary key for new data id:"+save); // commit the transaction transaction.commit(); // release resources session.close(); sessionFactory.close(); } 2. Run the test method testInsert() and the console output is as follows.
Hibernate: insert into user (user_id, user_name, password, email) values (?, ?, ?, ?) Primary key for new data id:3
3. Query the data in the user table of the database, and the result is as follows.
| id | user_id | user_name | password | email |
| 1 | 001 | admin | admin | 12345678@test.com |
| 2 | 002 | user | 123456 | 98765432@test.com |
| 3 | 003 | new user | 654321 | 14234567@test.com |
As can be seen from the above table, we successfully added a record to the user table using Hibernate.
Update record
Hibernate provides us with an update() method in the Session interface, which can be used to modify the records in the database table.
1. In the MyTest class, add a testUpdate() method with the following code.
/** * Modify the record */ @Test public void testUpdate() { //Load Hibernate core configuration file Configuration configuration = new Configuration().configure(); //Create a SessionFactory to get the Session connection object SessionFactory sessionFactory = configuration.buildSessionFactory(); //Get the session connection object Session session = sessionFactory.openSession(); // start transaction Transaction transaction = session.beginTransaction(); //create entity object User user = new User(); user.setId(3); //Set the fields to be modified user.setUserName("update user"); //Call the update() method directly to modify session.update(user); // commit the transaction transaction.commit(); // release resources session.close(); sessionFactory.close(); } 2. Execute the test method testUpdate(), and the console output is as follows.
Hibernate: update user set user_id=?, user_name=?, password=?, email=? where id=?
3. Query the data in the user table of the database, and the result is as follows.
| id | user_id | user_name | password | email |
| 1 | 001 | admin | admin | 12345678@test.com |
| 2 | 002 | user | 123456 | 98765432@test.com |
| 3 | (Null) | update user | (Null) | (Null) |
The update() method will update all fields of the specified record. For fields that we did not specify, Hibernate will modify it to the default value, which is obviously not the result we want.
Usually, we use the method of "query first and then modify" to avoid this problem. That is, first query the record that needs to be modified, obtain the entity object of the record, and then reassign the fields in the object, and finally use the object to perform the update operation.
4. Modify the code of the testUpdate() method, and use the method of "query first and then modify" to update. The code is as follows.
/** * Modify the record */ @Test public void testUpdate() { //Load Hibernate core configuration file Configuration configuration = new Configuration().configure(); //Create a SessionFactory to get the Session connection object SessionFactory sessionFactory = configuration.buildSessionFactory(); //Get the session connection object Session session = sessionFactory.openSession(); // start transaction Transaction transaction = session.beginTransaction(); // Now query the records that need to be modified User user = session.get(User.class, 3); //Set the fields to be modified user.setUserName("update user"); //Call the update() method directly to modify session.update(user); // commit the transaction transaction.commit(); // release resources session.close(); sessionFactory.close(); } 5. Re-execute the test method testUpdate() and the console output is as follows.
Hibernate: select user0_.id as id1_0_0_, user0_.user_id as user_id2_0_0_, user0_.user_name as user_nam3_0_0_, user0_.password as password4_0_0_, user0_.email as email5_0_0_ from user user0_ where user0_.id=? Hibernate: update user set user_id=?, user_name=?, password=?, email=? where id=?
6. Query the data in the user table of the database, as shown in the following table.
| id | user_id | user_name | password | email |
| 1 | 001 | admin | admin | 12345678@test.com |
| 2 | 002 | user | 123456 | 98765432@test.com |
| 3 | 003 | update user | 654321 | 14234567@test.com |
We successfully modified a record in the user table using Hibernate.
Remove record
In the Session interface, Hibernate provides us with a delete() method, which is used to delete records in the database table.
1. In the MyTest class, add a testDelete() method with the following code.
/** * Delete Record */ @Test public void testDelete() { //Load Hibernate core configuration file Configuration configuration = new Configuration().configure(); //Create a SessionFactory to get the Session connection object SessionFactory sessionFactory = configuration.buildSessionFactory(); //Get the session connection object Session session = sessionFactory.openSession(); // start transaction Transaction transaction = session.beginTransaction(); User user = new User(); user.setId(3); // delete the specified record session.delete(user); // commit the transaction transaction.commit(); // release resources session.close(); sessionFactory.close(); } 2. Execute the test method testDelete(), and the console output is as follows.
Hibernate: delete from user where id=?
3. Query the data in the data user table, and the result is as follows.
| id | user_id | user_name | password | email |
| 1 | 001 | admin | admin | 12345678@test.com |
| 2 | 002 | user | 123456 | 98765432@test.com |
We successfully deleted a record in the user table using Hibernate.
Query data
We know that Hibernate can query a specified piece of data through the get() method provided by the Session interface, but this method cannot query multiple or all database data.
Hibernate provides users with the following three query methods, all of which can be used to query multiple pieces of data.
- HQL query
- QBC query
- SQL query
HQL query
HQL full name: Hibernate Query Language. It is an object-oriented query language with a syntax similar to SQL. But HQL operates on entity class objects and their properties, not on fields in database tables. Among the various retrieval methods provided by Hibernate, HQL is the most widely used retrieval method.
1. Execute the following SQL statement in the database to add three pieces of user data using the gmail mailbox to the user table.
INSERT INTO `user`(user_id, user_name, password, email) VALUES ( '003', 'user2', 'user2', '9dfasdfa@gmail.com'); INSERT INTO `user`(user_id, user_name, password, email) VALUES ( '004', 'user3', 'user3', '76543345@gmail.com'); INSERT INTO `user`(user_id, user_name, password, email) VALUES ( '005', 'user4', 'user4', '234543546@gmail.com');
2. In the MyTest class, add a testHqlQuery() method, which is used to query all user data in the user table using gmail mailboxes. The code is as follows.
/** * Use HQL query */ @Test public void testHqlQuery() { //Load Hibernate core configuration file Configuration configuration = new Configuration().configure(); //Create a SessionFactory to get the Session connection object SessionFactory sessionFactory = configuration.buildSessionFactory(); //Get the session connection object Session session = sessionFactory.openSession(); // start transaction Transaction transaction = session.beginTransaction(); //Create HQL statement, the syntax is similar to SQL, but the operation is the entity class and its properties Query query = session.createQuery("from User where email like ?1"); //Query all users who use gmail mailboxes query.setParameter(1, "%@gmail.com%"); // get result set List<User> resultList = query.getResultList(); // loop through the result set for (User user : resultList) { System.out.println(user); } // commit the transaction transaction.commit(); // release resources session.close(); sessionFactory.close(); } 3. Execute the test method testHqlQuery(), the console output is as follows.
Hibernate: select user0_.id as id1_0_, user0_.user_id as user_id2_0_, user0_.user_name as user_nam3_0_, user0_.password as password4_0_, user0_.email as email5_0_ from user user0_ where user0_.email like ? com.iditect.www.po.User{id=4, userId='003', userName='user2', password='user2', email='9dfasdfa@gmail.com'} com.iditect.www.po.User{id=5, userId='004', userName='user3', password='user3', email='76543345@gmail.com'} com.iditect.www.po.User{id=6, userId='005', userName='user4', password='user4', email='234543546@gmail.com'} From the above console output, we can successfully query multiple pieces of data in the user table through HQL.
QBC query
The full name of QBC is Query By Criteria, which is a completely object-oriented database query technology. When querying the database through it, the application program does not need to provide query statements, but sets the data to be queried, query conditions, etc. through the related interfaces and classes in the QBC API.
In earlier versions of Hibernate, Criteria was commonly used to query data in the database in the following ways.
Criteria criteria = session.createCriteria(User.class); criteria.add(Restrictions.eq("userName", "admin")); List<Customer> list = criteria.list(); But after Hibernate 5.2, for security reasons, this method has been basically abandoned. Now QBC queries basically use CriteriaBuilder (a factory class) in the JPA (javax.persistence-api-xxx.jar) package to create CriteriaQuery objects to implement operations on the database.
The QBC API is located in the javax.persistence.criteria package and mainly includes the following interfaces:
| interface | Function description |
| CriteriaBuilder | Factory used to generate CriteriaQuery instance objects. |
| CriteriaQuery | The main query interface of QBC, through which the data to be queried can be set. |
| root | Specifies the root node object of the object graph that needs to be retrieved. |
| Selection | Used to specify the query statement. |
| Expression | A subinterface of the Selection interface, used to specify query expressions. |
| Predicate | A sub-interface of the Expression interface, used to specify query conditions. |
When querying with QBC, the following steps are required:
- Create a CriteriaBuilder instance from the Session object.
- Create an instance of CriteriaQuery from an instance of CriteriaBuilder.
- Create a Root instance object through the CriteriaBuilder object, and specify the root node object of the object graph to be queried. Hibernate will determine the main table in the query statement based on it.
- The query conditions are specified through the methods provided by CriteriaBuilder, and the Predicate object is returned. Hibernate determines the content of the where clause in the query statement according to it.
- Query data through the Query interface.
The CriteriaBuilder interface provides a series of methods for setting query conditions. These methods all return Predicate objects. The commonly used methods for setting conditional queries are as follows.
| method | describe |
| equal() | equal |
| notEqual() | not equal to |
| gt() | more than the |
| ge() | greater or equal to |
| lt() | less than |
| le() | less than or equal to |
| between() | Between |
| like() | resemblance |
| isNotEmpty() | not null |
| and() | and |
| or() | or |
1. In the MyTest class, add a testQbcQuery() method. In this method, use QBC to query the user data of all users who use gmail mailboxes in the user table. The code is as follows.
/** * QBC query */ @Test public void testQbcQuery() { //Load Hibernate core configuration file Configuration configuration = new Configuration().configure(); //Create a SessionFactory to get the Session connection object SessionFactory sessionFactory = configuration.buildSessionFactory(); //Get the session connection object Session session = sessionFactory.openSession(); // start transaction Transaction transaction = session.beginTransaction(); //Get the CriteriaBuilder object CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder(); //Build CriteriaQuery query object CriteriaQuery<User> criteria = criteriaBuilder.createQuery(User.class); //add query condition Root<User> from = criteria.from(User.class); Predicate like = criteriaBuilder.like(from.get("email"), "%@gmail.com%"); criteria.where(criteriaBuilder.and(like)); // get result set List<User> list = session.createQuery(criteria).getResultList(); // loop through the result set for (User user : list) { System.out.println(user); } // commit the transaction transaction.commit(); // release resources session.close(); sessionFactory.close(); } 2. Execute the test method testQbcQuery(), the console output is as follows.
Hibernate: select user0_.id as id1_0_, user0_.user_id as user_id2_0_, user0_.user_name as user_nam3_0_, user0_.password as password4_0_, user0_.email as email5_0_ from user user0_ where user0_.email like ? com.iditect.www.po.User{id=4, userId='003', userName='user2', password='user2', email='9dfasdfa@gmail.com'} com.iditect.www.po.User{id=5, userId='004', userName='user3', password='user3', email='76543345@gmail.com'} com.iditect.www.po.User{id=6, userId='005', userName='user4', password='user4', email='234543546@gmail.com'} From the above console output, we can successfully query multiple pieces of data in the user table through QBC.
SQL query
Hibernate also supports querying the database using native SQL statements.
1. In the MyTest class, add a testSqlQuery() method, which uses SQL to query the user data of all users who use gmail mailboxes in the user table. The code is as follows.
/** * SQL query */ @Test public void testSqlQuery() { //Load Hibernate core configuration file Configuration configuration = new Configuration().configure(); //Create a SessionFactory to get the Session connection object SessionFactory sessionFactory = configuration.buildSessionFactory(); //Get the session connection object Session session = sessionFactory.openSession(); // start transaction Transaction transaction = session.beginTransaction(); //build sql query NativeQuery sqlQuery = session.createSQLQuery("select * from user where email like '%gmail.com%'"); sqlQuery.addEntity(User.class); // get the result set List<User> resultList = sqlQuery.getResultList(); // loop through the result set for (User user : resultList) { System.out.println(user); } // commit the transaction transaction.commit(); // release resources session.close(); sessionFactory.close(); } 2. Execute the test method testSqlQuery(), and the console output is as follows.
Hibernate: select * from user where email like '%gmail.com%' com.iditect.www.po.User{id=4, userId='003', userName='user2', password='user2', email='9dfasdfa@gmail.com'} com.iditect.www.po.User{id=5, userId='004', userName='user3', password='user3', email='76543345@gmail.com'} com.iditect.www.po.User{id=6, userId='005', userName='user4', password='user4', email='234543546@gmail.com'} From the above console output, we can successfully use Hibernate to query multiple pieces of data in the user table through SQL.
More Tags
onbeforeunload schedule translate-animation naming-conventions encryption sql-injection shadow-dom delimiter unique-constraint tampermonkey
More Programming Guides
Other Guides
More Programming Examples