Table of Contents
Preparation
Program structure diagram
Home Java javaTutorial Use hibernate to implement operations on the person data table

Use hibernate to implement operations on the person data table

Jul 26, 2017 pm 04:39 PM
hibernate Simple

Hibernate is an open source ORM framework. As the name suggests, its core idea is ORM (Object Relational Mapping), which can operate information in the database through objects. It is said that developers are not very familiar with database SQL at the beginning. Statements, this also contributes to the power of hibernate. It does not require developers to be familiar with SQL statements to operate the database. Hibernate can automatically generate SQL statements and execute them automatically.

Using hibernate allows developers to fully use object-oriented thinking to operate the database, so the following demonstration will not contain a single SQL statement. If there is, please treat it as if I did not say this!

This article uses hibernate to implement simple basic add, delete, modify and query operations on a person data table.

Preparation

Environment: win7+eclipse

Toolkit: hibernate package, which can be downloaded. In this example, Version 4;

Database connection driver package, in this example mysql is used

Program structure diagram

##pojo layer entity class

package demo.pojo;
public class Person {private Integer id;private String name;private String gender;private Integer age;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getGender() {return gender;}public void setGender(String gender) {this.gender = gender;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}@Overridepublic String toString() {return "Person [id=" + id + ", name=" + name + ", gender=" + gender + ", age=" + age + "]";}}
Copy after login

Core configuration file hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- 以下四行分别为:数据库驱动类、Drivermanager获取连接的参数URL、用户名、密码  -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://127.0.0.1/web?characterEcoding=utf-8</property>
<property name="connection.username">root</property>
<property name="connection.password">123456</property>
<!-- 设置方言,hibernate会根据数据库的类型相应生成SQL语句 -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 控制台显示生成的sql语句,默认为false -->
<property name="show_sql">true</property>
<!-- 映射配置源文件的位置 -->
<mapping resource="demo/pojo/Person.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Copy after login

Mapping file Person.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<!-- name是实体类全名,table为数据表名 -->
<class name="demo.pojo.Person" table="Person">
<id name="id" column="id">
<!-- 主键生成方式,native是让hibernate自动识别 -->
<generator class="native"></generator>
</id>
<!--
Copy after login

Notes:
0. The name value is the attribute name in the entity class, and column is the field name in the data table;
1. When the attribute name in the entity class is the same as the corresponding data table field name, the following column can be omitted, and hibernate will automatically Match, for example, age below;
2. On the contrary, when the attribute name in the entity class is different from the field name of the corresponding data table, both items must be written, for example, gender and sex below
-->

<property name="name" column="name"></property>
<property name="gender" column="sex"></property>
<property name="age"></property>
</class>
</hibernate-mapping>
Copy after login

Session Factory Class

package demo.util;
import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;import org.hibernate.service.ServiceRegistry;import org.hibernate.service.ServiceRegistryBuilder;
public class HibernateSessionFactory {private static SessionFactory factory;private static ThreadLocal<Session> thread = new ThreadLocal<Session>();private static String path = "hibernate.cfg.xml";private static Configuration config = new Configuration();static {config.configure(path);ServiceRegistry service = new ServiceRegistryBuilder()//定义一个服务注册机.applySettings(config.getProperties()).buildServiceRegistry();factory = config.buildSessionFactory(service);//创建Session工厂类}/** * 从hibernate的session工厂类里创建一个session * @return * */public static Session getSession() {Session session = thread.get();if(session == null || !session.isOpen()) {session = factory.openSession();thread.set(session);}return session;}public static void closeSession() {Session session = thread.get();if(session != null && session.isOpen()) {session.close();thread.set(null);}}}
Copy after login

DAO layer encapsulates the methods of data operations

package demo.dao;
import java.io.Serializable;import org.hibernate.Session;import org.hibernate.Transaction;import demo.pojo.Person;import demo.util.HibernateSessionFactory;
public class PersonDaoImpl {//增删改查,此处以增为例public boolean add(Person p) {Session session = HibernateSessionFactory.getSession();//创建SessionTransaction trans = session.beginTransaction();//开启事务try {Serializable id = session.save(p);//添加记录并获取主键值System.out.println(id+"为获取的主键值");//控制台查看主键值trans.commit();//提交事务return true;} catch (Exception e) {trans.rollback();//获取异常,则事务回滚} finally {HibernateSessionFactory.closeSession();//关闭Session}return false;}}
Copy after login

Test class TestPerson

package demo.test;
import org.junit.Test;import demo.dao.PersonDaoImpl;import demo.pojo.Person;
public class TestPerson {@Testpublic void testAdd() {//创建一个人类对象Person p = new Person();p.setName("张三");p.setGender("男");p.setAge(18);//创建dao层类对象并调用添加方法PersonDaoImpl dao = new PersonDaoImpl();dao.add(p);}}
Copy after login

The above is the detailed content of Use hibernate to implement operations on the person data table. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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 Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The easiest way to query the hard drive serial number The easiest way to query the hard drive serial number Feb 26, 2024 pm 02:24 PM

The hard disk serial number is an important identifier of the hard disk and is usually used to uniquely identify the hard disk and identify the hardware. In some cases, we may need to query the hard drive serial number, such as when installing an operating system, finding the correct device driver, or performing hard drive repairs. This article will introduce some simple methods to help you check the hard drive serial number. Method 1: Use Windows Command Prompt to open the command prompt. In Windows system, press Win+R keys, enter "cmd" and press Enter key to open the command

How to write a simple student performance report generator using Java? How to write a simple student performance report generator using Java? Nov 03, 2023 pm 02:57 PM

How to write a simple student performance report generator using Java? Student Performance Report Generator is a tool that helps teachers or educators quickly generate student performance reports. This article will introduce how to use Java to write a simple student performance report generator. First, we need to define the student object and student grade object. The student object contains basic information such as the student's name and student number, while the student score object contains information such as the student's subject scores and average grade. The following is the definition of a simple student object: public

How to write a simple online reservation system through PHP How to write a simple online reservation system through PHP Sep 26, 2023 pm 09:55 PM

How to write a simple online reservation system through PHP. With the popularity of the Internet and users' pursuit of convenience, online reservation systems are becoming more and more popular. Whether it is a restaurant, hospital, beauty salon or other service industry, a simple online reservation system can improve efficiency and provide users with a better service experience. This article will introduce how to use PHP to write a simple online reservation system and provide specific code examples. Create database and tables First, we need to create a database to store reservation information. In MyS

Quick Start: Use Go language functions to implement a simple library management system Quick Start: Use Go language functions to implement a simple library management system Jul 30, 2023 am 09:18 AM

Quick Start: Implementing a Simple Library Management System Using Go Language Functions Introduction: With the continuous development of the field of computer science, the needs of software applications are becoming more and more diverse. As a common management tool, the library management system has also become one of the necessary systems for many libraries, schools and enterprises. In this article, we will use Go language functions to implement a simple library management system. Through this example, readers can learn the basic usage of functions in Go language and how to build a practical program. 1. Design ideas: Let’s first

How to write a simple music recommendation system in C++? How to write a simple music recommendation system in C++? Nov 03, 2023 pm 06:45 PM

How to write a simple music recommendation system in C++? Introduction: Music recommendation system is a research hotspot in modern information technology. It can recommend songs to users based on their music preferences and behavioral habits. This article will introduce how to use C++ to write a simple music recommendation system. 1. Collect user data First, we need to collect user music preference data. Users' preferences for different types of music can be obtained through online surveys, questionnaires, etc. Save data in a text file or database

How to integrate Hibernate in SpringBoot project How to integrate Hibernate in SpringBoot project May 18, 2023 am 09:49 AM

Integrating Hibernate in SpringBoot Project Preface Hibernate is a popular ORM (Object Relational Mapping) framework that can map Java objects to database tables to facilitate persistence operations. In the SpringBoot project, integrating Hibernate can help us perform database operations more easily. This article will introduce how to integrate Hibernate in the SpringBoot project and provide corresponding examples. 1.Introduce dependenciesIntroduce the following dependencies in the pom.xml file: org.springframework.bootspring-boot-starter-data-jpam

How to write a simple minesweeper game in C++? How to write a simple minesweeper game in C++? Nov 02, 2023 am 11:24 AM

How to write a simple minesweeper game in C++? Minesweeper is a classic puzzle game that requires players to reveal all the blocks according to the known layout of the minefield without stepping on the mines. In this article, we will introduce how to write a simple minesweeper game using C++. First, we need to define a two-dimensional array to represent the map of the Minesweeper game. Each element in the array can be a structure used to store the status of the block, such as whether it is revealed, whether there are mines, etc. In addition, we also need to define

MySQL Table Design Guide: Create a Simple Employee Attendance Sheet MySQL Table Design Guide: Create a Simple Employee Attendance Sheet Jul 01, 2023 pm 01:54 PM

MySQL Table Design Guide: Creating a Simple Employee Attendance Table In enterprise management, employee attendance management is a crucial task. In order to accurately record and count employee attendance, we can use the MySQL database to create a simple employee attendance sheet. This article will guide you how to design and create this table, and provide corresponding code examples. First, we need to identify the required fields for the employee attendance sheet. Generally speaking, employee attendance sheets need to contain at least the following fields: employee ID, date, working time, off-duty time

See all articles