Introduction to Hibernate II (add, delete, modify and check)

Keywords: Session Hibernate SQL Junit

Hibernate's addition, deletion, modification and query

  1. increase
    There are many ways to add, such as save, persist, savaoroupdate and merge.
    The use method is as follows.
    The code here follows the previous section
package test;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.junit.Test;
import entity.User;
public class UserTest {
    @Test
    public void testSave() {
        Configuration configuration=new Configuration().configure(); // Instantiate profile
        ServiceRegistry serviceRegistry=new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); // Instantiation service registration
        SessionFactory sessionFactory=configuration.buildSessionFactory(serviceRegistry); // Get Session factory
        Session session=sessionFactory.openSession(); // Generate a session
        session.beginTransaction(); // Open transaction

        User user = new User();
        user.setName("Zhang San");
        user.setBirthDay(new Date(System.currentTimeMillis()));
        session.save(user);

        session.getTransaction().commit(); // Submission of affairs
        session.close(); // Close session
        sessionFactory.close(); // Close session factory
    }

    @Test
    public void testMerge(){

            Configuration configuration=new Configuration().configure(); // Instantiate profile
            ServiceRegistry serviceRegistry=new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); // Instantiation service registration
            SessionFactory sessionFactory=configuration.buildSessionFactory(serviceRegistry); // Get Session factory
            Session session=sessionFactory.openSession(); // Generate a session
            session.beginTransaction(); // Open transaction

            User user = new User();
            user.setName("Zhang San");
            user.setBirthDay(new Date(System.currentTimeMillis()));
            session.merge(user);

            session.getTransaction().commit(); // Submission of affairs
            session.close(); // Close session
            sessionFactory.close(); // Close session factory
    }

    @Test
    public void testPersist(){
        Configuration configuration=new Configuration().configure(); // Instantiate profile
        ServiceRegistry serviceRegistry=new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); // Instantiation service registration
        SessionFactory sessionFactory=configuration.buildSessionFactory(serviceRegistry); // Get Session factory
        Session session=sessionFactory.openSession(); // Generate a session
        session.beginTransaction(); // Open transaction

        User user = new User();
        user.setName("Zhang San");
        user.setBirthDay(new Date(System.currentTimeMillis()));
        session.persist(user);

        session.getTransaction().commit(); // Submission of affairs
        session.close(); // Close session
        sessionFactory.close(); // Close session factory
    }
}

2. delete
Delete a record using delete
This code segment is added in the above class. It is required to write this code to the above class

@Test
    public void testDelete(){
        Configuration configuration=new Configuration().configure(); // Instantiate profile
        ServiceRegistry serviceRegistry=new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); // Instantiation service registration
        SessionFactory sessionFactory=configuration.buildSessionFactory(serviceRegistry); // Get Session factory
        Session session=sessionFactory.openSession(); // Generate a session
        session.beginTransaction(); // Open transaction


        User user = new User();
        user.setId(2);
        //In this way, deletion can only be done by id
        //user.setName("Zhang San 2"); / / the statement cannot be deleted
        session.delete(user);

        session.getTransaction().commit(); // Submission of affairs
        session.close(); // Close session
        sessionFactory.close(); // Close session factory
    }

3. amendment
Modify use Update, SaveOrUpdate, merge method
There is no code parsing here. Basically, it is the use of Entity and session objects.

4 query
There are many ways to query
1) Local SQL query
A key
String sql = "select * from t_user2 where id<:value";
Query query = session.createSQLQuery(sql).addEntity(User.class); / / if you do not add entity here, you will not be able to use it later
query.setInteger("value",4);

Here, the SQL statements printed by the console are:
Hibernate: select * from t_user2 where id

@Test
    public void testSQLQuery(){
Configuration configuration=new Configuration().configure(); // Instantiate profile
        ServiceRegistry serviceRegistry=new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); // Instantiation service registration
        SessionFactory sessionFactory=configuration.buildSessionFactory(serviceRegistry); // Get Session factory
        Session session=sessionFactory.openSession(); // Generate a session
        session.beginTransaction(); // Open transaction

        String sql = "select * from t_user2 where id<:value";
        Query query = session.createSQLQuery(sql).addEntity(User.class);
        query.setInteger("value", 4);
        List<User> list = query.list();
        for(User s:list){
            System.out.println(s);
        }
        session.getTransaction().commit(); // Submission of affairs
        session.close(); // Close session
        sessionFactory.close(); // Close session factory
    }

2) HQL query
Similar to SQL in form

@Test
    public void testHQLQuery(){
        Configuration configuration=new Configuration().configure(); // Instantiate profile
        ServiceRegistry serviceRegistry=new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); // Instantiation service registration
        SessionFactory sessionFactory=configuration.buildSessionFactory(serviceRegistry); // Get Session factory
        Session session=sessionFactory.openSession(); // Generate a session
        session.beginTransaction(); // Open transaction

        String hql = "from User where id<:value";
        Query query = session.createQuery(hql);
        query.setInteger("value", 4);
        List<User> list = query.list();
        for(User s:list){
            System.out.println(s);
        }
        session.getTransaction().commit(); // Submission of affairs
        session.close(); // Close session
        sessionFactory.close(); // Close session factory
    }

Paging and unique values
Use when paging
query.setFirstResult(offset);
query.setMaxResults(length);
query.uniqueResult() returns a unique object when it is determined that our query value is unique.

3) QBC query
Not much to say, just go to the code and use JUnit to execute in the previous class.

@Test
    public void testQBC(){
        Configuration configuration=new Configuration().configure(); // Instantiate profile
        ServiceRegistry serviceRegistry=new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); // Instantiation service registration
        SessionFactory sessionFactory=configuration.buildSessionFactory(serviceRegistry); // Get Session factory
        Session session=sessionFactory.openSession(); // Generate a session
        session.beginTransaction(); // Open transaction

        Criteria criteria = session.createCriteria(User.class);
        List<User> list = criteria.list();
        for(User s:list){
            System.out.println(s);
        }


        session.getTransaction().commit(); // Submission of affairs
        session.close(); // Close session
        sessionFactory.close(); // Close session factory
    }


    @Test
    public void testQBC2(){
        Configuration configuration=new Configuration().configure(); // Instantiate profile
        ServiceRegistry serviceRegistry=new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); // Instantiation service registration
        SessionFactory sessionFactory=configuration.buildSessionFactory(serviceRegistry); // Get Session factory
        Session session=sessionFactory.openSession(); // Generate a session
        session.beginTransaction(); // Open transaction

        Criteria criteria = session.createCriteria(User.class);
        Criterion criterion = Restrictions.lt("id",4);
        criteria.addOrder(Order.desc("id"));
        criteria.add(criterion);
        List<User> list = criteria.list();
        for(User s:list){
            System.out.println(s);
        }


        session.getTransaction().commit(); // Submission of affairs
        session.close(); // Close session
        sessionFactory.close(); // Close session factory
    }

Posted by L0j1k on Thu, 02 Apr 2020 15:28:25 -0700