JAVA framework / HIBERNATE / HIBERNATE textbook series (a) - basic - HIBERNATE based introductory tutorial examples

JAVA framework / HIBERNATE / HIBERNATE textbook series (a) - basic - HIBERNATE based introductory tutorial examples

# More content, sign up for

Use JDBC database-related functions do develop will do a lot of repetitive work, such as creating a connection, the connection is closed, the property is mapped to the field one by one. Hibernate package it all up so easy and simple database access code is also easier to maintain .

For the first time there will be a Hibernate configuration process more steps later use, very simple.

Reading : Framework-based program to run successfully, JAR packages for the version, the correctness of the configuration file has stringent requirements, anywhere in the wrong, it will result in the framework of the program to fail. If you are first learning this framework, be sure to strictly follow the instructions of the tutorial, to imitate the operation until a successful run to see the effect. After a successful first time, confidence will have a better idea of foreshadowing, then according to their doubts on the "success" of the code originally wanted to make changes and adjustments, which can greatly save time learning, improve efficiency, Never one to tamper with, creating obstacles to their learning

Step 1: Before learning effect look
Step 2: Create database
Step 3: Create a table
Step 4: Create a java project
Step 5: Import hibernate jar package depends
Step 6: Create entity classes
Step 7: Configure Product.hbm.xml
step 8: configure hibernate.cfg.xml
step 9: test class TestHibernate
step 10: Fundamentals FIG
step 11: project run
step 12: information about Run.WARNING
step 13: exercise

Step 1: Look at the effect of prior learning

This example demonstrates how to use the database to insert a hibernate data.
As shown, this product data iphone7, is inserted from the hibernate
Here Insert Picture Description

Step 2: Create a database

First, prepare the database test
if the database is not installed, please refer to install mysql-server

Note : the newly installed database account password is root: admin, subsequent configuration, the account password is used for this. If the password is not this, this knowledge download area (click to enter) can not run up to run the project, so try to change the password for the admin, change your password ways: Changing the root password
create database test;

Step 3: Create a table

Preparation Table product_, has three fields, namely,
the primary key id (from growth)
name string format
price floating-point format,
use test;

CREATE TABLE product_ (
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(30) ,
price float ,
PRIMARY KEY (id)
) DEFAULT CHARSET=UTF8;

Step 4: Create a java project

Create a java project

Step 5: Import jar package depends hibernate

In the download area (click to enter) download lib.rar, and unzip it into hibernate project directory: e: \ project \ hibernate \ lib this position.
Then import the jar package for the java project
leader packet steps : Right-project-> property-> java build path-> libaries-> add external jars
Note Always use the jar package I offer compatibility jar package between different versions of hibernate question, if you are using downloaded from the official website hibernate different versions of Jar package, then follow this tutorial arrangement does not necessarily go through.
Here Insert Picture Description

Step 6: Create entity classes

Product for the entity class mapping table 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;
  }
    
}

Step 7: Configure Product.hbm.xml

Com.how2java.pojo a new packet at the Product.hbm.xml profile, corresponding to a mapping database Product class product_ Table
Note : filename Product.hbm.xml P must be capitalized, and class to be consistent

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

表示类Product对应表product_
<id name="id" column="id">
  <generator class="native">
  </generator>
</id>

表示属性id,映射表里的字段id
<generator class="native"> 意味着id的自增长方式采用数据库的本地方式

如果是连接oracle数据库,可以指定sequnce作为id自增长方式
<property name="name" />

这里配置的时候,只写了属性name,没有通过column="name" 显式的指定字段,那么字段的名字也是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>

步骤 8 : 配置 hibernate.cfg.xml

src目录下创建 hibernate.cfg.xml
配置访问数据库要用到的驱动,url,账号密码等等
其他配置及含义:

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

这表示使用MYSQL方言。 什么方言呢? 因为在代码层面,开发人员不用关心底层到底用Oracle还是Mysql,写的代码都是一样的。 可是Oracle和Mysql所用的sql语句的语法是有所区别的,那么这件事就交给Hibernate来做了。这个时候就需要告诉Hibernate底层用的是什么数据库,它才知道应该用什么样的“方言” 去对话。

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

这是Hibernate事务管理方式,即每个线程一个事务

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

这表示是否在控制台显示执行的sql语句

<property name="hbm2ddl.auto">update</property>

这表示是否会自动更新数据库的表结构,有这句话,其实是不需要创建表的,因为Hibernate会自动去创建表结构

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

这表示Hibernate会去识别Product这个实体类
<?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>

步骤 9 : 测试类 TestHibernate

创建一个Product对象,并通过hibernate把这个对象,插入到数据库中

hibernate的基本步骤是:

  1. 获取SessionFactory
  2. 通过SessionFactory 获取一个Session
  3. 在Session基础上开启一个事务
  4. 通过调用Session的save方法把对象保存到数据库
  5. 提交事务
  6. 关闭Session
  7. 关闭SessionFactory

步骤 9 :测试类 TestHibernate

Here Insert Picture Description

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();
   }

}

步骤 10 : 基本原理图

Hibernate applications through a Product object into the database table product_
hibernate.cfg.xml configuration file provides links to a database of basic information about
account password database driver ip port
Product.hbm.xml provide an object mapping table and
which table corresponds ? What attributes correspond to what field
Here Insert Picture Description

Step 11: You can run the project

Download area (click to enter) have knowledge of this correspondence, you can run the project.
If you own configuration always unsuccessful, run after decompression download the top right corner of hibernate.rar, and then compare the difference with their own code to find the problem.

Step 12: Warning message about running

Will appear as shown in the warning after running three lines of information, it is because there is no slf4j configuration, so the warning message does not affect the operation.

To solve this problem, it is necessary to introduce the log4j jar and configuration files, and the current Hibernate learning has nothing to do, in order to focus on learning Hibernate itself, the owners do not provide log4j those things. Does not affect the operation, learn down Well
 关于运行警告信息

Step 13: Exercise

Reference present embodiment, a Category class doing exercises.
Category has attributes id, name. A correspondence table category, a field id, name

Creating a Category, set its name to "Category 1", and then inserted into the database through hibernate

More, CLICK HERE

Published 32 original articles · won praise 182 · views 10000 +

Guess you like

Origin blog.csdn.net/weixin_44092440/article/details/101176684