Download area
File name File size
lib.rar 6m
hibernate.rar 6m

Tool version compatibility problem
use JDBC Doing database related function development will do a lot of repetitive work , For example, create a connection , Close the connection , Map the fields to the attributes one by one . Hibernate It encapsulates all this , Make database access easy and simple , The code is also easier to maintain .

First use Hibernate There will be a multi-step configuration process , Use later , It's simple .

Must read : Framework based programs run successfully , For JAR Package version , The correctness of the configuration file has strict requirements , Anything goes wrong , Will cause the framework program to fail . If you are learning this framework for the first time , Be sure to follow the instructions of the tutorial strictly , Completely imitate the operation , Until you successfully see the running effect . After the first success , Confidence , Ideas will have a better cushion , Then according to their doubts , stay “ success ” Make the desired changes and adjustments to your code , This can greatly save learning time , increase of efficiency , Don't change it at once , Create obstacles to your learning

Step 1 : Look at the effect before learning   
Step 2 : Create database   
Step 3 : Create table   
Step 4 : Create a java project   
Step 5 : Import hibernate Rely on jar Bag   
Step 6 : Create an entity class   
Step 7 : to configure Product.hbm.xml   
Step 8 : to configure hibernate.cfg.xml   
Step 9 : Test class TestHibernate   
Step 10 : Basic schematic diagram   
Step 11 : Runnable project   
Step 12 : Warning information about running   
Step 13 : practice   

Step 1 :

Look at the effect before learning

edit top fracture
This example demonstrates how to use hibernate Insert a piece of data into the database .
As shown in the figure , This one iphone7 Product data for , namely from hibernate Inserted
 Look at the effect before learning
First prepare the database test
If the database is not installed , Please refer to Install mysql-server

notes : The newly installed database account password is root:admin, In the subsequent configuration , I also use this account password . If the password is not this , The runnable items in the upper right corner of this knowledge point can't run , So try to change the password to admin, Password modification method : modify root password
create database test;
create database test;
Prepare the table product_, have 3 Fields , namely
Primary key id( Self growth )
String format name
Floating point format price
use test; CREATE TABLE product_ ( id int(11) NOT NULL AUTO_INCREMENT, name varchar(30) , price float , PRIMARY KEY (id) ) DEFAULT CHARSET=UTF8;
use test;

CREATE TABLE product_ (
  name varchar(30) ,
  price float ,
 Create a java project
Step 5 :

Import hibernate Rely on jar Bag

edit top fracture
Download... In the upper right corner lib.rar, And unzip it to hibernate Under the project directory : e:\project\hibernate\lib This position .
Then for this java project Import jar Bag
Guide Package steps : Right click project->property->java build path->libaries->add external jars
notes Be sure to use the jar Bag ,hibernate Between different versions jar There is a compatibility problem with the package , If you use from hibernate Different versions downloaded from the official website Jar Bag , Then follow the configuration of this tutorial , It doesn't necessarily work .
 Import hibernate Rely on jar Bag
Entity class Product Used to map tables in the database product_
package com.how2java.pojo; public class Product { int id; String name; float price; public int getId() { return id; } public void setId(int id) { = id; } public String getName() { return name; } public void setName(String name) { = name; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } }
In the bag com.how2java.pojo Next Create a new configuration file Product.hbm.xml, Used to map Product Class corresponds to... In the database product_ surface
notes : File name Product.hbm.xml P Be sure to capitalize , Be consistent with the class

<class name="Product" table="product_">

express class Product corresponding surface product_

<id name="id" column="id">
<generator class="native">

express attribute id, In the mapping table field id
<generator class="native"> signify id The self growth mode of adopts the local mode of database

If it's a connection oracle database , sure appoint sequnce As id Self growth mode

<property name="name" />

When configuring here , Only the attributes are written name, Failed column="name" Explicitly specify the field , So the name of the field is also name.
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" ""> <hibernate-mapping package="com.how2java.pojo"> <class name="Product" table="product_"> <id name="id" column="id"> <generator class="native"> </generator> </id> <property name="name" /> <property name="price" /> </class> </hibernate-mapping>
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

<hibernate-mapping package="com.how2java.pojo">
	<class name="Product" table="product_">
		<id name="id" column="id">
			<generator class="native">
		<property name="name" />
		<property name="price" />
Step 8 :

to configure hibernate.cfg.xml

edit top fracture
stay src catalogue Create... Under hibernate.cfg.xml
Configure the driver used to access the database ,url, Account, password, etc
Other configurations and meanings :

<property name="dialect">org.hibernate.dialect.MySQLDialect</property>

This means using MYSQL Dialect . What dialect ? Because at the code level , Developers don't have to worry about what the bottom layer is using Oracle still Mysql, The code written is the same . But Oracle and Mysql Used sql The syntax of statements is different , Then leave it to Hibernate Here we go . This is the time to tell Hibernate What database is used at the bottom , It knows what to use “ Dialect ” Go talk .

<property name="current_session_context_class">thread</property>

This is Hibernate Transaction management , That is, one transaction per thread

<property name="show_sql">true</property>

This indicates whether the executed... Is displayed on the console sql sentence

<property name="">update</property>

This indicates whether the table structure of the database will be automatically updated , There is this sentence , In fact, you don't need Create table of , Because Hibernate Will automatically create a table structure

<mapping resource="com/how2java/pojo/Product.hbm.xml" />

This means Hibernate Will identify Product This entity class
<?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" ""> <hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8</property> <property name="connection.username">root</property> <property name="connection.password">admin</property> <!-- SQL dialect --> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <property name="current_session_context_class">thread</property> <property name="show_sql">true</property> <property name="">update</property> <mapping resource="com/how2java/pojo/Product.hbm.xml" /> </session-factory> </hibernate-configuration>
Create a Product Object , And through hibernate Put this object , Insert into the database

hibernate The basic steps are :
1. obtain SessionFactory
2. Through SessionFactory Get a Session
3. stay Session Start a transaction based on
4. By calling Session of save Method to save the object to the database
5. Commit transaction
6. close Session
7. close SessionFactory
 Test class  TestHibernate
package com.how2java.test; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import com.how2java.pojo.Product; public class TestHibernate { public static void main(String[] args) { SessionFactory sf = new Configuration().configure().buildSessionFactory(); Session s = sf.openSession(); s.beginTransaction(); Product p = new Product(); p.setName("iphone7"); p.setPrice(7000);; s.getTransaction().commit(); s.close(); sf.close(); } }
The application passes Hibernate hold One Product Object inserted into the database product_ In the table
hibernate.cfg.xml Configuration files provide basic information about linked databases
account number password Drive database ip port
Product.hbm.xml Provide the mapping relationship between objects and tables
Corresponding to which table ? What properties , What field does it correspond to
 Basic schematic diagram
In the upper right corner, there is the... Corresponding to this knowledge point , Runnable project .
If your configuration is always unsuccessful , Download the... In the upper right corner hibernate.rar Unzip and run , Then compare the difference with your own code , Find the problem .
Step 12 :

Warning information about running

edit top fracture
After running, three lines of warning messages will appear as shown in the figure , This is because there is no slf4j to configure , So the warning message , It does not affect the operation .

To solve this problem , Need to introduce log4j of jar And configuration files , And the current Hibernate Learning has nothing to do with , To focus on Hibernate In their own learning , The webmaster will not provide log4j Those things . Without affecting the operation , Let's study further
 Warning information about running
Step 13 :


edit top fracture   Wrong posture , get half the results with double the effort ! Click to see the correct posture for the exercise
Refer to this example , Make a Category Class practice .
Category There are properties id,name. The corresponding table is category, The field is id,name

Create a Category, Set its name by " Classification 1" , Then pass hibernate Insert into database

The official account of programming , Follow and get the latest tutorials and promotions in real time , thank you .

Q & A area    
2021-07-02 Report an error according to the prompt
The stars reflect the moon

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". SLF4J: Defaulting to no-operation (NOP) logger implementation SLF4J: See for further details. WARNING: An illegal reflective access operation has occurred WARNING: Illegal reflective access by (file:/D:/eclipseCode/hibernate/lib/dom4j-1.6.1.jar) to method$LocatorProxy.getEncoding() WARNING: Please consider reporting this to the maintainers of WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations WARNING: All illegal access operations will be denied in a future release Exception in thread "main" org.hibernate.exception.JDBCConnectionException: Cannot open connection at org.hibernate.exception.SQLStateConverter.convert( at org.hibernate.exception.JDBCExceptionHelper.convert( at org.hibernate.exception.JDBCExceptionHelper.convert( at org.hibernate.jdbc.ConnectionManager.openConnection( at org.hibernate.jdbc.ConnectionManager.getConnection( at org.hibernate.jdbc.JDBCContext.connection( at org.hibernate.transaction.JDBCTransaction.begin( at org.hibernate.impl.SessionImpl.beginTransaction( at com.how2java.test.TestHibernate.main( Caused by: com.mysql.jdbc.exceptions.MySQLNonTransientConnectionException: Client does not support authentication protocol requested by server; consider upgrading MySQL client at com.mysql.jdbc.SQLError.createSQLException( at com.mysql.jdbc.MysqlIO.checkErrorPacket( at com.mysql.jdbc.MysqlIO.checkErrorPacket( at com.mysql.jdbc.MysqlIO.secureAuth411( at com.mysql.jdbc.MysqlIO.doHandshake( at com.mysql.jdbc.Connection.createNewIO( at com.mysql.jdbc.Connection.<init>( at com.mysql.jdbc.NonRegisteringDriver.connect( at java.sql/java.sql.DriverManager.getConnection( at java.sql/java.sql.DriverManager.getConnection( at org.hibernate.connection.DriverManagerConnectionProvider.getConnection( at org.hibernate.jdbc.ConnectionManager.openConnection( ... 5 more

1 One answer

Answer time :2021-07-06
Failed to load class "org.slf4j.impl.StaticLoggerBinder". Import slf4j-simple-1.6.1.jar After normal , I don't understand what's going on

The answer has been submitted successfully , Auditing . Please My answer Check the answer record at , thank you
answer Or code please Fill in at least one , If you have a problem , Please ask again , Otherwise, the webmaster may not see

2021-05-21 Follow the steps exactly , Why report mistakes

How to operate this

2 One answer

Thousands of evening stars
Answer time :2021-08-06
You have to hibernate.cfg.xml Put it in src/main/java Directory instead of the bottom of the file directory src catalogue

Answer time :2021-07-06
Import slf4j-simple-1.6.1.jar, The principle is not clear

The answer has been submitted successfully , Auditing . Please My answer Check the answer record at , thank you
answer Or code please Fill in at least one , If you have a problem , Please ask again , Otherwise, the webmaster may not see

2020-12-26 .hbm.xml It's always red, but it works well
2020-09-15 Say a problem you have encountered new Configuration() report errors
2020-08-31 Report this error :Failed to instantiate SLF4J LoggerFactory

Too many questions , Page rendering is too slow , To speed up rendering , Only a few questions are displayed on this page at most . also 89 Previous questions , please Click to view

Please... Before asking questions land
The question has been submitted successfully , Auditing . Please My question Check the question record at , thank you
about JAVA Frame -Hibernate-hello hibernate Your questions

Try to provide Screenshot code and Abnormal information , Help to analyze and solve problems . You can also enter this station QQ Group communication : 496725845
Ask questions and try to provide complete code , Environment description , The more conducive to the recurrence of the problem , The faster your question can be answered .
Have questions about the code in the tutorial , Please provide which step , Which line is in doubt , This makes it easy to quickly locate the problem , Improve the speed at which questions are answered
In the thousands of questions that already exist , A considerable proportion , Because of the use of and webmaster Different versions of the development environment Resulting in , For example jdk, eclpise, idea, mysql,tomcat Wait, the version of the software is inconsistent .
Please use the same version as the webmaster , You can save yourself a lot of learning time . The webmaster sorted out the software versions used in teaching , It's all here , Convenient for everyone to download : /k/helloworld/helloworld-version/1718.html

Upload screenshot