Use hibernate to implement operations on the person data table
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
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 + "]";}}
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>
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>
<!--
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>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);}}}
DAO layer encapsulates the methods of data operationspackage 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;}}
Test class TestPersonpackage 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);}}
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!

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.

JavaisnotentirelyplatformindependentduetoJVMvariationsandnativecodeintegration,butitlargelyupholdsitsWORApromise.1)JavacompilestobytecoderunbytheJVM,allowingcross-platformexecution.2)However,eachplatformrequiresaspecificJVM,anddifferencesinJVMimpleme

TheJavaVirtualMachine(JVM)isanabstractcomputingmachinecrucialforJavaexecutionasitrunsJavabytecode,enablingthe"writeonce,runanywhere"capability.TheJVM'skeycomponentsinclude:1)ClassLoader,whichloads,links,andinitializesclasses;2)RuntimeDataAr

Javaremainsagoodlanguageduetoitscontinuousevolutionandrobustecosystem.1)Lambdaexpressionsenhancecodereadabilityandenablefunctionalprogramming.2)Streamsallowforefficientdataprocessing,particularlywithlargedatasets.3)ThemodularsystemintroducedinJava9im

Javaisgreatduetoitsplatformindependence,robustOOPsupport,extensivelibraries,andstrongcommunity.1)PlatformindependenceviaJVMallowscodetorunonvariousplatforms.2)OOPfeatureslikeencapsulation,inheritance,andpolymorphismenablemodularandscalablecode.3)Rich

The five major features of Java are polymorphism, Lambda expressions, StreamsAPI, generics and exception handling. 1. Polymorphism allows objects of different classes to be used as objects of common base classes. 2. Lambda expressions make the code more concise, especially suitable for handling collections and streams. 3.StreamsAPI efficiently processes large data sets and supports declarative operations. 4. Generics provide type safety and reusability, and type errors are caught during compilation. 5. Exception handling helps handle errors elegantly and write reliable software.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.
