hibernate Series Notes (1) - - hibernate Addition, Deletion and Amendment

Keywords: Java Hibernate Session xml Database

Hibernate additions, deletions and modifications

1. First, we need to know what Hibernate is.

Hibernate is a lightweight ORMapping object. Mainly used to achieve the mapping between Java and database tables, in addition to providing data query and data acquisition methods.

It can greatly reduce the time of manual use of SQL and JDBC to process data during development, and liberate 95% of the tasks of programmers.

2. What is ORM Object-Relational-Mapping Object Relational Mapping

ORM: It maps to database tables through Java objects. It can complete the operation of database tables by manipulating Java objects. (If you're using Dbutils, you need to write sql statements in Java classes, but ORM doesn't.)

Hibernate is a complete ORM framework that generates the underlying SQL only by manipulating objects.

Next, go directly to the theme:

First look at the basic process of using hibernate! Here's a simple flow chart

1. Create projects:

Create a web project with myeclipse

2. Import hibernate-related shelving packages into projects

Step 3: Configure hibernate

Create a new XML file under the src directory named hibernate.cfg.xml (of course, you may not call this name, but you need to modify the code accordingly). Copy the following:

<?xml version="1.0" encoding="UTF-8"?>
  <!DOCTYPE hibernate-configuration PUBLIC
      "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
      "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
      
  <hibernate-configuration>
      <!-- Configuring Session Factory   hibernate Core Management Database Connection Pool -->
      <session-factory>
          <!-- 1.Configure database connection parameters -->
         <!-- 1.1 To configure jdbc Four basic connection parameters -->
         <property name="hibernate.connection.username">root</property>
         <property name="hibernate.connection.password">root</property>
         <property name="hibernate.connection.url">jdbc:mysql:///hibernateexec</property>
         <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
         <!-- 1.2 To configure hibernate Dialects in use -->
         <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
     
         <!-- 2.Configure other related properties -->
         <!-- 2.1 Automatic table building -->
         <property name="hibernate.hbm2ddl.auto">update</property>
         <!-- 2.2 Output in log sql -->
         <property name="hibernate.show_sql">true</property>    
         <!-- 2.3 Format sql -->
         <property name="hibernate.format_sql">true</property> 
         
         <!-- Open transaction -->
         <property name="hibernate.connection.autocommit">true</property>
         
         <!-- To configure c3p0 Database connection pool -->
         <property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
         
         <property name="hibernate.c3p0.min_size">5</property>
         <property name="hibernate.c3p0.max_size">50</property>
         <property name="hibernate.c3p0.timeout">120</property>
         <property name="hibernate.c3p0.idle_test_period">3000</property>
                    
         <!-- 3.Load the mapping file -->
         <mapping resource="com/study/model/Customer.hbm.xml"/> 
         
     </session-factory>    
 
 </hibernate-configuration>
Configure hibernate.cfg.xml

Here's a reminder: you don't need to create the customer table manually, but the database hibernateexec is created manually.

Step 4. Create entities and mapping files

public class Customer {

    private int id;
    private String name;
    private int age;
    private String city;
    private String addr;
}
/*
 * Provide set and get methods
 */
Customer entity

Mapping files and entity objects are in the same package:

 <?xml version="1.0" encoding="UTF-8"?>
  <!DOCTYPE hibernate-mapping PUBLIC 
      "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
      "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
  <hibernate-mapping>
      <! - Complete the mapping of entity classes and data tables - >.
      The mapping between classes and tables - > 1.
      <!-- 
          The complete class name to be mapped by name
         Table mapping to database table names
         catalog maps to the name of the database
      -->
     <class name="com.study.model.Customer" table="customer" catalog="hibernateexec">
          <!--2. Mapping of attributes in classes and data columns in tables - >
           <! - 2.1 Primary Key - >
           <!-- 
               Name attribute name (in class)
               Column column names (in tables)
               Type data type
            -->
          <id name="id" column="id" type="int">
              <! - Configure Primary Key Generation Policy Primary Key Automatic Growth - > Configure Primary Key Generation Policy
              <generator class="identity"></generator>
          </id>
          <! - 2.2 Common Attributes - >
          <!-- 
              Name attribute name (in class)
              Column column names (in tables)
              Type data type (you can also write String directly)
           -->
          <property name="name" column="name" type="java.lang.String"></property>    
          <property name="age" column="age" type="int"></property>
          <! - It can also be written separately - >.
          <property name="city">
              <column name="city" sql-type="varchar(20)"></column>
          </property>
          <! - If nothing is written, the attribute name of the defau lt class and the column name in the database are all addr and the type is varchar - >.
       <property name="addr"></property> 
            
     </class>
     
 </hibernate-mapping>
Customer.hbm.xml

Step 5: Create SessionFactory objects

Step 6: Get the Session object for related operations

Step 5 and Step 6 I am with you. Step 6 we find that the first four steps are the same regardless of adding, deleting, and checking. In fact, we can extract a tool class and call it again to speed up the efficiency.

import java.util.List;
 import org.hibernate.Query;
 import org.hibernate.SQLQuery;
 import org.hibernate.Session;
 import org.hibernate.SessionFactory;
 import org.hibernate.Transaction;
 import org.hibernate.cfg.Configuration;
 import org.junit.Test;
 
 import com.study.model.Customer;
 
 public class HibernateTest { 
        /*
         * Save data
         */
         @Test
         public void testInsert() {
             // Instantiated Configuration Object Load Mapping File Load hibernate.cfg.xml
             Configuration configuration = new Configuration().configure();
             // Create a Session Factory
             SessionFactory sessionFactory = configuration.buildSessionFactory();
             // Create session
             Session session = sessionFactory.openSession();
             // Open transaction
             Transaction transaction = session.beginTransaction();
             // Write your own logical code
             Customer customer = new Customer();
            customer.setName("Xiao Huang");
            customer.setAge(40);
            customer.setCity("Beijing");
             // Direct preservation
            session.save(customer);
 
             // Submission of affairs
             transaction.commit();
             session.close();
             sessionFactory.close();
         } 
     
     //Query all
     @Test
     public  void testFindAllByHQL(){
         // Instantiated Configuration Object Load Mapping File Load hibernate.cfg.xml
         Configuration configuration = new Configuration().configure();
         // Create a Session Factory
         SessionFactory sessionFactory = configuration.buildSessionFactory();
         // Create session
         Session session = sessionFactory.openSession();
         // Open transaction
         Transaction transaction = session.beginTransaction();
         
         //To write HQL Sentence(Class and attribute-oriented queries 
         String hql =" from Customer";//Here is Customer Not table name but class name query Customer
         Query query =session.createQuery(hql);
         
         List<Customer> customers=query.list();
         System.out.println(customers);
         
         
         // Submission of affairs
         transaction.commit();
        session.close();
         sessionFactory.close();
     }
 
     // delete
     @Test
     public void testDelete() {
         // Instantiated Configuration Object Load Mapping File Load hibernate.cfg.xml
         Configuration configuration = new Configuration().configure();
         // Create a Session Factory
         SessionFactory sessionFactory = configuration.buildSessionFactory();
         // Create session
         Session session = sessionFactory.openSession();
         // Open transaction
         Transaction transaction = session.beginTransaction();
         
        Customer customer =new Customer();
        customer.setId(2);
         session.delete(customer);
         

         // Submission of affairs
         transaction.commit();
         session.close();
         sessionFactory.close();
    }
 
     // modify
     @Test
     public void testUpdate() {
         // Instantiated Configuration Object Load Mapping File Load hibernate.cfg.xml
         Configuration configuration = new Configuration().configure();
         // Create a Session Factory
         SessionFactory sessionFactory = configuration.buildSessionFactory();
         // Create session
         Session session = sessionFactory.openSession();
         // Open transaction
         Transaction transaction = session.beginTransaction();
 
         Customer customer = (Customer) session.get(Customer.class, 2);
         customer.setCity("Hangzhou");
         session.update(customer);
 
         // Submission of affairs
         transaction.commit();
         session.close();
         sessionFactory.close();
 
     }
 
     // Query Basis id query
     @Test
     public void testFindById() {
         // Instantiated Configuration Object Load Mapping File Load hibernate.cfg.xml
         Configuration configuration = new Configuration().configure();
         // Create a Session Factory
         SessionFactory sessionFactory = configuration.buildSessionFactory();
         // Create session
         Session session = sessionFactory.openSession();
         // Open transaction
         Transaction transaction = session.beginTransaction();
 
         Customer customer = (Customer) session.get(Customer.class, 1);
         System.out.println(customer);
 
         // Submission of affairs
         transaction.commit();
         session.close();
         sessionFactory.close();
     }
 }
hibernate additions, deletions and modifications

Running effect: When you run the first add-on user, the end-of-run database automatically creates customer tables and adds data to the tables.

In this way, the basic additions and deletions are checked through hibernate.

This is the end of this article, there are shortcomings welcome your advice, thank you!

Posted by Lamez on Mon, 08 Apr 2019 10:36:34 -0700