This is the 10th day of my participation in the August Text Challenge.More challenges in August

Hibernate is an open source object-relational mapping framework, which makes a very lightweight object encapsulation of JDBC. It establishes a mapping relationship between POJOs and database tables. It is an automatic ORM framework, Hibernate can automatically generate SQL statements, automatically execute, Allowing Java programmers to manipulate databases using object programming thinking at will, Hibernate can be used anywhere using JDBC, either in Java client programs or in Servlet/JSP Web applications. By the way, what ORM is. ORM: Object relational mapping, is a program technology, simply put, is our program entity class and database table to establish a corresponding relationship. So why do we have object-relational mapping? For example, when you are developing an application, you probably write a lot of code in the data access layer to save, delete, read object information from the database, and so on. You write a lot of methods in daOs to read object data, change state objects, and so on, and a lot of that code is repetitive. Object mapping relationship gives the program a powerful ability, so that developers only master object-oriented thinking to operate the database, that is, to make a mapping between relational database and business entity objects, so that we do not need to deal with complex SQL statements in the specific operation of business objects, Just manipulate it as you would an object.

HelloWorld

With some basic knowledge of Hibernate behind us, let’s write an introductory project for Hibernate. First we need to write hibernate configuration file, create hibernate. Cfg. XML file in SRC directory:


      
<! DOCTYPEhibernate-configuration PUBLIC
		"- / / Hibernate/Hibernate Configuration DTD / 3.0 / EN"
		"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
	<session-factory>
    	<! -- Configure basic information for connecting to the database -->
		<property name="connection.username">root</property>
		<property name="connection.password">123456</property>
		<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="connection.url">jdbc:mysql:///test</property>

		<! Configure basic information about Hibernate
		<property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>

		<! Print SQL on console when performing operation -->
		<property name="show_sql">true</property>

		<! Do you want to format SQL?
		<property name="format_sql">true</property>

		<! -- Specify the policy for automatic table generation -->
		<property name="hbm2ddl.auto">update</property>

		<! -- Specify the associated.hbm.xml file -->
		<mapping
			resource="com/itcast/hibernate/helloworld/Account.hbm.xml" />
	</session-factory>
</hibernate-configuration>
Copy the code

This is to configure some relevant information. Then we create a Bean class Account:

package com.itcast.hibernate.helloworld;

public class Account {

	private Integer id;
	private String name;
	private double money;

	public Account(a) {}public Account(String name, double money) {
		this.name = name;
		this.money = money;
	}

	public Integer getId(a) {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName(a) {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public double getMoney(a) {
		return money;
	}

	public void setMoney(double money) {
		this.money = money;
	}

	@Override
	public String toString(a) {
		return "Account [id=" + id + ", name=" + name + ", money=" + money + "]"; }}Copy the code

Next we need to create the configuration file for object-relational mapping and create a new account.hbm. XML file in the same directory as this class:


      
<! DOCTYPEhibernate-mapping PUBLIC "- / / Hibernate/Hibernate Mapping DTD / 3.0 / EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
	<! Alter table Account -->
    <class name="com.itcast.hibernate.helloworld.Account" table="ACCOUNT">
        <! -- The name in the id tag is the name of the attribute in the class; Name in the colum tag is the column name in the table -->
        <id name="id" type="java.lang.Integer">
            <column name="ID" />
            <! -- specify primary key generation native -->
            <generator class="native" />
        </id>
        <! -- property specifies other columns that are not id columns -->
        <property name="name" type="java.lang.String">
            <column name="NAME" />
        </property>
        <property name="money" type="double">
            <column name="MONEY" />
        </property>
    </class>
</hibernate-mapping>
Copy the code

Briefly, the purpose of this configuration file is to make a mapping between classes and tables. Then let’s write the test code:

		// create a SessionFactory object
		SessionFactory sessionFactory = null;
		// create a Configuration object that corresponds to hibernate's basic Configuration information and object-relational mapping information
		// The default file is hibernate.hbm. XML. If your configuration file name is hibernate.hbm. XML, use no arguments
		Configuration configuration = new Configuration().configure();
		sessionFactory = configuration.buildSessionFactory();
		// create a Session object
		Session session = sessionFactory.openSession();
		// start transaction
		Transaction transaction = session.beginTransaction();
		// 4. Perform the save operation
		Account account = new Account("Zhang".1000);
		session.save(account);
		// 5
		transaction.commit();
		// close Session
		session.close();
		// Close SessionFactory
		sessionFactory.close();
Copy the code

Then run the test code, Hibernate will save the data to the database, and if you don’t have the table, Hibernate will automatically create the table for us and insert the data. Because hibernate version of the problem, so there will be a lot of pit, specific reported what wrong we can baidu solve their own. My version of Hibernate here is 5.x.

+ - + - + -- -- -- -- -- -- -- -- -- -- -- -- + | | ID NAME | MONEY | +, + + -- -- -- -- -- -- -- -- -- -- -- -- -- + | | 1000 | | zhang SAN + 1 - + -- -- -- -- -- - + -- -- -- -- -- -- -- + 1 row in the set (0.00 SEC)Copy the code

When creating persistent classes, pay attention to the following:

  • A constructor with no arguments must be provided

Hibernate needs to instantiate persistent classes using constructor.newinstance ()

  • Provide an identity property

Normally mapped to a primary key field of a data table, without this property some functionality will not work

  • Declare access methods for persistent class fields of a class
  • Use non-final classes

Generating proxies at run time is an important feature of Hibernate. If a persistent class does not implement any interface, Hibernate will use CGLIB to generate proxies, and if a final class is used, CGLIB proxies cannot be generated

  • Override the equals and hashCode methods

If you need to put an instance of a persistent class into a Set (when associated mapping is required), you should override both methods

Introduction case we finished writing, I believe that the configuration information of the two configuration files can be understood, the comments are also written very clear, so about the test code of some class API, here respectively introduced.

  1. The Configuration:

The Configuration class manages Hibernate Configuration information, including the following: You can create a Configuration file using the following methods: Database URL, username, password, JDBC driver class, database Dialect, database connection pool Configuration cfg = new Configuration(); Configuration CFG = new Configuration().configure(); Configuration’s configure method also supports parameter access: File File = new File(” filename “); Configuration cfg = new Configuration().configure(file); 2. The SessionFactory: A compiled memory image of a single database mapping, it’s a thread safe SessionFactory object and once it’s constructed, it’s given specific configuration information. SessionFactory is a factory that produces sessions. Constructing a SessionFactory is very resource-intensive, Generally, only one SessionFactory object is initialized in an application. Session is an interactive operation between the application program and the database, while the single-threaded object is the center of Hibernate operation. All persistent objects must be managed by Session before they can be persisted. This object has a short life cycle. The Session object has a level 1 cache, where all persistence-layer operations are cached until they are explicitly flush

update

Speaking of inserting data, here’s how to use Hibernate to do the update.

  • session.save(obj); Save an object
  • session.update(obj); Update an object
  • session.saveOrUpdate(obj); [Method of saving or updating]

If no primary key is set, save. If the primary key is set, the update operation is performed. If the primary key is not set, there is no error!

		SessionFactory sessionFactory = null;
		Configuration configuration = new Configuration().configure();
		sessionFactory = configuration.buildSessionFactory();
		Session session = sessionFactory.openSession();
		Transaction transaction = session.beginTransaction();
		Account account = session.get(Account.class, 1);
		account.setMoney(2000);
		session.update(account);
		transaction.commit();
		session.close();
		sessionFactory.close();
Copy the code

Run and query the database:

+ - + - + -- -- -- -- -- -- -- -- -- -- -- -- + | | ID NAME | MONEY | +, + + -- -- -- -- -- -- -- -- -- -- -- -- -- + | | 2000 | | zhang SAN + 1 - + -- -- -- -- -- - + -- -- -- -- -- -- -- + 1 row in the set (0.00 SEC)Copy the code

The query

Next comes the query.

		SessionFactory sessionFactory = null;
		Configuration configuration = new Configuration().configure();
		sessionFactory = configuration.buildSessionFactory();
		Session session = sessionFactory.openSession();
		Transaction transaction = session.beginTransaction();
		Account account = session.load(Account.class, 1);
		System.out.println(account);
		transaction.commit();
		session.close();
		sessionFactory.close();
Copy the code

Running results:

delete

Finally, delete.

		SessionFactory sessionFactory = null;
		Configuration configuration = new Configuration().configure();
		sessionFactory = configuration.buildSessionFactory();
		Session session = sessionFactory.openSession();
		Transaction transaction = session.beginTransaction();
		Account account = session.get(Account.class, 1);
		session.delete(account);
		transaction.commit();
		session.close();
		sessionFactory.close();
Copy the code

Running results:

mysql> select * from account; The Empty set (0.00 SEC)Copy the code

conclusion

The operation of add, delete, change and check is very simple. As long as you can do one, the others will be able to do it, because the truth is the same. There’s more to using Hibernate than that, of course, but this article is just to get you started, so I’m going to cover some of the more advanced features in the advanced section.