An introduction to Hibrenate

Posted by dcampbell18 on Mon, 20 May 2019 22:06:46 +0200

1. Create a database
New database

create database test;

New table:
Primary key ID (self-growth)
name in string format
price in floating-point format

use test;

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

2. Create a java project and import the packages needed for the project
3. Create the entity class product corresponding to the table

package com.ljx;

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

4. Configure Product.hbm.xml (a series of configurations for connecting to databases)

<?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.ljx">
    <class name="product" table="prodyct_">
        <id name="id" column="id">
            <generator class="native"></generator>
        </id>
        <property name="name"/>
        <property name="price"/>

    </class>
</hibernate-mapping>
 <id name="id" column="id">
          <generator class="native"></generator>
 </id>

Represents the attribute id, the field ID in the mapping table

 Generator class= "native"> means that the self-growth mode of id adopts the local mode of database.
<property name="name"/>

Only the attribute name is written, and the name of the field in the corresponding table is also name without explicitly specifying the field by column="name".

5. Configure hibernate.cfg.xml (a series of configurations about hibernate)

<?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/test2?characterEncoding=UTF-8</property>
        <property name="connection.username">root</property>
        <property name="connection.password"></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/ljx/product.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

1. Configure the driver, url, account password used to access the database
2. <property name="dialect">org.hibernate.dialect.MySQL Dialect</property> indicates that the database used by Hibernate's underlying layer is mysql.
3. <property name="current_session_context_class">thread</property> is Hibernate transaction management mode, that is, a thread corresponds to a transaction.
4. <property name= "show_sql">true </property> indicates whether the executed mysql statement is displayed on the console
5. <property name="hbm2ddl.auto">update</property> indicates whether the table structure of the database is automatically updated.
6. <mapping resource= "com/ljx/product.hbm.xml"/> indicates that Hibernate will identify Product as an entity class.

6. Test class TestHibernate

package com.ljx;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class testHibernate {

    public static void main(String[] args){
        Configuration configuration = new Configuration();
        configuration.configure("com/ljx/hibernate.cfg.xml");

        SessionFactory sf = configuration.buildSessionFactory();

        Session s = sf.openSession();
        s.beginTransaction();

        product p = new product();
        p.setName("xiaoa");
        p.setPrice(1000);
        s.save(p);

        s.getTransaction().commit();
        s.close();
        sf.close();
    }
}

Create a Product object and insert it into the database through hibernate
The basic steps of hibernate are:
1. Get the hibernate configuration file
2. Get SessionFactory
3. Get Session through Session Factory
4. Open a transaction on Session
5. Save the object to the database by calling the save method of Session
6. Submission
7. Close Session
8. Close SessionFactory

7.hibernate realizes adding, deleting, modifying and checking

package com.ljx;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class testHibernate2 {
    Configuration configuration;
    SessionFactory sf;
    Session s;
    Transaction t;

    public testHibernate2(){
        configuration = new Configuration();
        configuration.configure("com/ljx/hibernate.cfg.xml");
        sf= configuration.buildSessionFactory();
    }

    public void add(product product){
        s = sf.openSession();
        t = s.beginTransaction();
        s.save(product);
        t.commit();

        s.close();
    }

    public void delete(int id){
        s = sf.openSession();
        t = s.beginTransaction();
        s.delete(s.get(product.class,id));
       // product p = (product)s.get(product.class,new Integer(2));
        t.commit();

        s.close();
    }

    public void update(product product){
        s = sf.openSession();
        t = s.beginTransaction();
        s.update(product);
        t.commit();
        s.close();
    }

    public product getById(int id){
        s = sf.openSession();
        t = s.beginTransaction();
        product p = (product)s.get(product.class,id);
        t.commit();
        s.close();
        return p;
    }
    public static void main(String[] args){

        testHibernate2 th = new testHibernate2();

        //increase
        product p_1 = new product();
        p_1.setName("add");
        p_1.setPrice(10);
        th.add(p_1);

        //delete
        int id_2 = 3;
        th.delete(id_2);

        //modify
        product p_3 = new product();
        p_3.setId(1);
        p_3.setName("update");
        p_3.setPrice(20);
        th.update(p_3);

        //lookup
        int id_4 = 1;
        product p_4 = th.getById(id_4);
        System.out.println(p_4.getId());
        System.out.println(p_4.getName());
        System.out.println(p_4.getPrice());
    }
}

Before operation:


After operation:

Console output:

Topics: Hibernate Session Database xml