tags: Hibernate


preface

You’ve already covered Hibernate in general from the previous article and have the foundation for a quick start case,…. This blog post focuses on the Hibernate API

Why don’t we look at what objects are used in the quickstart code and go through them one by one


    public static void main(String[] args) {

        // Create an object
        User user = new User();
        user.setPassword("123");
        user.setCellphone("122222");
        user.setUsername("nihao");

        // Get the load configuration management class
        Configuration configuration = new Configuration();

        Hibernate. Cfg. XML file is loaded by default without an argument.
        configuration.configure();

        // Create a Session factory object
        SessionFactory factory = configuration.buildSessionFactory();

        // Get the Session object
        Session session = factory.openSession();

        // If you use Hibernate to operate a database, you need to start a transaction and get the transaction object
        Transaction transaction = session.getTransaction();

        // Start the transaction
        transaction.begin();

        // Add the object to the database
        session.save(user);

        // Commit the transaction
        transaction.commit();

        / / close the Session
        session.close();
    }

Copy the code

Configuration

Configuration management class: A class that manages configuration files

It has a subclass AnnotationConfiguration, which means that annotations can be used instead of XML configuration files to configure the corresponding information

The configure method

The configure() method is used to load the configuration file

  • Method of loading the master configuration file
    • If a parameter is specified, the path configuration file for the parameter is loaded
    • ** If no parameter is specified, hibernate. Cfg. XML in SRC/is loaded by default

BuildSessionFactory method

BuildSessionFactory () is used to create the Session factory


SessionFactory

SessionFactory–>Session factory, also can be said to represent hibernate.cfg. XML file… Hibernate. Cfg. XML has a

node

OpenSession method

Create a Session object

GetCurrentSession method

Create or retrieve a Session object


Session

Session is the most important object of Hibernate. Session maintains a Connection. Whenever Hibernate is used to operate a database, Session objects are needed

We usually have the following methods in the DAO layer, and Session provides corresponding methods to implement them!


public interface IEmployeeDao {

	void save(Employee emp);
	void update(Employee emp);
	Employee findById(Serializable id);
	List<Employee> getAll(a);
	List<Employee> getAll(String employeeName);
	List<Employee> getAll(int index, int count);
	void delete(Serializable id);
	
}

Copy the code

The update operation

We used the save(Objcet O) method in quick start, which saves the object in the database by calling it. The Session object also provides other methods for updating the database

  • session.save(obj); Save an object
  • session.update(obj); Update an object
  • session.saveOrUpdate(obj); [Method of saving or updating]
    • ** No primary key is set, perform save; **
    • ** If the primary key is set, the update operation is performed. **
    • If the primary key is not set, there is no error!

Let’s use the update() method…. Since it is the update operation, so certainly need to set the primary key, do not set the primary key, how can the database know you want to update what. Change the record with ID 1 to the following:


        user.setId(1);
        user.setPassword("qwer");
        user.setCellphone("1111");
        user.setUsername("zhongfucheng");
Copy the code


The primary key query

Query database records by primary key to return a JavaBean object

  • session.get(javaBean.class, int id); [Pass in the corresponding class and ID to query]
  • session.load(javaBean.class, int id); [Support lazy loading]

User overwrites toString() to see what happens:


       User user1 = (User) session.get(User.class, 1);
        System.out.println(user1);

Copy the code


HQL query

HQL: Hibernate Query Language is an object-oriented query language provided by Hibernate

  • Queries for objects and properties of objects. .

SQL: Struct Query Language

  • Query tables and columns

HQL is an object-oriented query language that can be used to query all data.


        Query query = session.createQuery("FROM User");

        List list = query.list();
        System.out.println(list);
Copy the code

Of course, it can also pass parameters into the query

        Query query = session.createQuery("FROM User WHERE id=?");

        // Here? Numbers start at 0, not like JDBC starts at 1!
        query.setParameter(0, user.getId());

        List list = query.list();
        System.out.println(list);

Copy the code


QBC query

QBC queries: Query by Criteria Fully object-oriented queries

From the above HQL query, we can find: HQL query is the basis of SQL, because still need to write a small part of the SQL code…. QBC queries are fully object-oriented queries… But we use it less

Let’s see how it works:


        // Create criteria objects for the User object
        Criteria criteria = session.createCriteria(User.class);

        // Add a condition
        criteria.add(Restrictions.eq("id".1));

        // Query all data
        List list = criteria.list();
        System.out.println(list);
Copy the code


Local SQL query

Sometimes, if SQL is too complex to rely on HQL queries, we need to use native SQL for complex queries!

However, it has one drawback: it is not cross-platform… So we have already configured the database “dialect” in the master configuration file.

Let’s use it briefly:


        // Encapsulate all records as User objects and store them in the List collection
        SQLQuery sqlQuery = session.createSQLQuery("SELECT * FROM user").addEntity(User.class);

        List list = sqlQuery.list();

        System.out.println(list);

Copy the code

BeginTransaction method

When you start a transaction, you return a transaction object…. Hibernate states that all database operations must take place in a transactional environment or an error will be reported!


Hibernate execution flowchart

If you find this article helpful, give the author a little encouragement