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 .
Correct
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 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
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
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_ ( id int(11) NOT NULL AUTO_INCREMENT, name varchar(30) , price float , PRIMARY KEY (id) ) DEFAULT CHARSET=UTF8;
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 .
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) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.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"> </generator> </id> 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" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <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" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <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>
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="hbm2ddl.auto">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" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <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="hbm2ddl.auto">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
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.save(p); 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
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 .
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
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
1 One answer
qiaozq Jump to the problem location 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
2021-05-21
Follow the steps exactly , Why report mistakes
2 One answer
Thousands of evening stars Jump to the problem location 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
qiaozq Jump to the problem location 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
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
|