search
HomeJavajavaTutorialIntroduction to Hibernate and examples
Introduction to Hibernate and examplesJun 25, 2017 pm 01:35 PM
javagetting StartedExampleSimple

1. Introduction to Hibernate

In many scenarios, we do not need to use JdbcTemplate to directly operate SQL statements. At this time, we can use ORM tools to save a lot of code and development time. . ORM tools can shift the focus from error-prone SQL code to how to implement the real needs of the application.

Spring's support for ORM frameworks provides integration points with these frameworks and some additional services:

  • Supports integration of Spring declarative transactions;

  • Transparent exception handling;

  • Thread-safe, lightweight template class;

  • DAO support class ;

  • Resource management.

Hibernate is an open source ORM framework that is very popular in the developer community.

2. Spring+Hibernate instance

1. Create a database table

mysqlCreate a new database store, and then execute the following sql:

1 create table Category (2 Id int not null,3 Name varchar(80) null,4 constraint pk_category primary key (Id)5 );6 7 INSERT INTO category(id,Name) VALUES (1,'女装');8 INSERT INTO category(id,Name) VALUES (2,'美妆');9 INSERT INTO category(id,Name) VALUES (3,'书籍');
db_store.sql

2. Code structure

The IDE I use is IdeaIU and I build the project through maven , configure spring through xml. The completed code structure is:

Introduction to Hibernate and examples

3. Create the entity class Category

class Category{
    private int cateId;

    private String cateName;

    //次数省略get,set方法
@Override
    public String toString() {
        return "id="+cateId+" name="+cateName;
    }
}

 

<dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.3.5.Final</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.30</version>
        </dependency>
    </dependencies>

 

5. Configure applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns="http://www.springframework.org/schema/beans" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans  http://www.springframework.org/schema/tx ">


    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/store"></property>
        <property name="username" value="root"></property>
        <property name="password" value="root"></property>
    </bean>

    <bean id="sessionFactory"
          class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:hibernate/hibernate.cfg.xml"/>
    </bean>

    <tx:annotation-driven/>
    <bean id="transactionManager"
          class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

    <bean id="categoryDao" class="CategoryDao">
        <constructor-arg ref="sessionFactory"></constructor-arg>
    </bean>
</beans>

 

dataSource is nothing special, just No more explanation. Take a look at a few other points:

①hibernate sessionFactory:

The main interface required to use Hibernate is org.hibernate.Session. The Session interface provides the most basic CRUD and other Data access capabilities. Through Hibernate's Session interface, the application's Repository can meet all persistence needs. The standard way to obtain a Hibernate Session object is to use the implementation class of the Hibernate SessionFactory interface.

There are two main properties set in the sessionFactory configuration: dataSource sets the data connection, and configLocation sets the path to the hibernate configuration file.

②Transaction

If the database operation supports transactions, you need to configure and transactionManager.

6.hibernate configuration

①hibernate.cfg.xml

<?xml version=&#39;1.0&#39; encoding=&#39;utf-8&#39;?>
        <!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>
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="show_sql">true</property>
    <mapping resource="hibernate/Category.hbm.xml"/>
</session-factory>
</hibernate-configuration>

 

②Category.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="Category" table="Category">
        <id name="cateId" column="id">
            <generator class="native"/>
        </id>
        <property name="cateName" column="name"/>
    </class>
</hibernate-mapping>

 

7. Data access implementation class CategoryDao

If the method wants to support transactions, it needs to be annotated @Transactional.

public class CategoryDao {
    private SessionFactory sessionFactory;

    public CategoryDao(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    private Session currentSession() {
        return sessionFactory.getCurrentSession();
    }

    @Transactional
    public void save(Category category) {
        currentSession().save(category);
    }

    @Transactional
    public void update(Category category){
        currentSession().update(category);
    }

    @Transactional
    public void delete(int id) {
        Query query = currentSession().createSQLQuery("DELETE FROM category WHERE Id=::ID");
        query.setInteger("::ID", id);
        query.executeUpdate();
    }

    @Transactional
    public int count() {
        return getAll().size();
    }

    @Transactional
    public Category getById(int id) {
        Criteria criteria=currentSession().createCriteria(Category.class);
        criteria.add(Restrictions.eq("id",id));
        return (Category) criteria.uniqueResult();
    }

    @Transactional
    public List<Category> getAll() {
        return currentSession().createCriteria(Category.class).list();
    }
}

 

8. Test

@ContextConfiguration(locations = "classpath:applicationContext.xml")
@RunWith(SpringJUnit4ClassRunner.class)
public class testCategoryDao {
    @Autowired
    private CategoryDao categoryDao;

    @Test
    public void testAdd() {
        Category category = new Category();
        category.setCateId(4);
        category.setCateName("母婴");

        categoryDao.save(category);
    }

    @Test
    public void testUpdate() {
        Category category = new Category();
        category.setCateId(4);
        category.setCateName("男装");

        categoryDao.update(category);
    }


    @Test
    public void testGetById() {
        int id = 4;
        Category category = categoryDao.getById(id);

        if(category==null){
            System.out.println("not exist");
        }else {
            System.out.println(category.toString());
        }
    }

    @Test
    public void testGetAll() {
        List<Category> categories = categoryDao.getAll();
        for (Category item : categories) {
            System.out.println(item);
        }
    }

    @Test
    public void testCount() {
        int count = categoryDao.count();
        System.out.println(count);
    }

    @Test
    public void testDelete() {
        int id = 4;
        categoryDao.delete(id);
    }
}

The above is the detailed content of Introduction to Hibernate and examples. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
带你搞懂Java结构化数据处理开源库SPL带你搞懂Java结构化数据处理开源库SPLMay 24, 2022 pm 01:34 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于结构化数据处理开源库SPL的相关问题,下面就一起来看一下java下理想的结构化数据处理类库,希望对大家有帮助。

Java集合框架之PriorityQueue优先级队列Java集合框架之PriorityQueue优先级队列Jun 09, 2022 am 11:47 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于PriorityQueue优先级队列的相关知识,Java集合框架中提供了PriorityQueue和PriorityBlockingQueue两种类型的优先级队列,PriorityQueue是线程不安全的,PriorityBlockingQueue是线程安全的,下面一起来看一下,希望对大家有帮助。

完全掌握Java锁(图文解析)完全掌握Java锁(图文解析)Jun 14, 2022 am 11:47 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于java锁的相关问题,包括了独占锁、悲观锁、乐观锁、共享锁等等内容,下面一起来看一下,希望对大家有帮助。

一起聊聊Java多线程之线程安全问题一起聊聊Java多线程之线程安全问题Apr 21, 2022 pm 06:17 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于多线程的相关问题,包括了线程安装、线程加锁与线程不安全的原因、线程安全的标准类等等内容,希望对大家有帮助。

Java基础归纳之枚举Java基础归纳之枚举May 26, 2022 am 11:50 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于枚举的相关问题,包括了枚举的基本操作、集合类对枚举的支持等等内容,下面一起来看一下,希望对大家有帮助。

详细解析Java的this和super关键字详细解析Java的this和super关键字Apr 30, 2022 am 09:00 AM

本篇文章给大家带来了关于Java的相关知识,其中主要介绍了关于关键字中this和super的相关问题,以及他们的一些区别,下面一起来看一下,希望对大家有帮助。

java中封装是什么java中封装是什么May 16, 2019 pm 06:08 PM

封装是一种信息隐藏技术,是指一种将抽象性函式接口的实现细节部分包装、隐藏起来的方法;封装可以被认为是一个保护屏障,防止指定类的代码和数据被外部类定义的代码随机访问。封装可以通过关键字private,protected和public实现。

Java数据结构之AVL树详解Java数据结构之AVL树详解Jun 01, 2022 am 11:39 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于平衡二叉树(AVL树)的相关知识,AVL树本质上是带了平衡功能的二叉查找树,下面一起来看一下,希望对大家有帮助。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.