Hibernate学习笔记——Introduction和简单例子

本文介绍Hibernate框架的基本使用方法,包括配置核心文件hibernate.cfg.xml、创建实体类与映射文件,以及通过Hibernate工具类实现数据的持久化操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Hibernate是一个开源的对象关系映射的框架。它对JDBC做了轻量级的封装,而我们java程序员可以使用面向对象的思想来操纵数据库。最近好像MyBatis比较流行一些。Hibernate相对来说比较简单。Hibernate适用的场景很多,可以使CS的项目,也可以是BS的web项目。在很大程度上能减少程序员直接在代码中嵌入SQL的烦恼。至于是不是比用JDBC直接连接数据库方便也是见仁见智。当然Hibernate对事务的管理以及缓存机制还有它的可取之处。

一个简单的Hibernate的例子:

Hibernate的核心配置文件hibernate.cfg.xml,这个文件是可以改名的只要我们在读取配置文件的不使用默认值,指定文件名就可以了。放在工程src目录下即可:

<?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/hibernate</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>

        <!-- JDBC connection pool (use the built-in) -->
        <!--  <property name="connection.pool_size">1</property>-->

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
		<property name="javax.persistence.validation.mode">none</property> 
		<!-- <property name="javax.persistence.validation.mode">none</property>  -->
        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
        <!-- <property name="hbm2ddl.auto">update</property> -->

        <mapping resource="com/smile/hibernate/model/Student.hbm.xml"/>

    </session-factory>

</hibernate-configuration>
配置文件都比较简单,这里默认的是Mysql的数据库,如果是Oracle数据库的话就需要修改一下配置,具体的配置可以参照Hibernate的doc来进行配置。

还有一个配置也是需要注意的:

<!-- Drop and re-create the database schema on startup 这个配置会校验数据库 validate 创建表 create 更新表 update 结束后drop create-drop     Automatically validates or exports schema DDL to the database when the SessionFactory is created. With create-drop, the database schema will be dropped when the SessionFactory is closed explicitly.  -->
        <property name="hbm2ddl.auto">create</property>


这句配置的意思是在启动的时候自动创建或者删除表。如果有一个插入的操作,而数据库中没有表,Hibernate会自己帮你创建出表。不建议使用。

<mapping resource="com/smile/hibernate/model/Student.hbm.xml"/>
配置了一个映射。这里的明明规则最好是类.hbm.xml便于识别。可放在与类文件同级目录下。

<?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.smile.hibernate.model">
   <class name="Student" table="student">
        <id name="id" column="id"></id>
        <property name="name" column="name"></property>
        <property name="sex" column="sex"></property>
        <property name="age" column="age"></property>
    </class>
</hibernate-mapping>
熟悉数据库的可以看出来,id表示为,其他都是属性。

Student.java类:

package com.smile.hibernate.model;

public class Student {
	private int id;
	private String name;
	private String sex;
	private int age;
	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 String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}

}
写一个Hibernate的工具类:

package com.smile.hibernate.util;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
	private static final SessionFactory sessionFactory = buildSessionFactory();

	private static SessionFactory buildSessionFactory() {
		try {
			// Create the SessionFactory from hibernate.cfg.xml
//			SessionFactory sc = new Configuration().configure().buildSessionFactory(
//					new StandardServiceRegistryBuilder().build());
			Configuration cfg = new Configuration().configure();
			SessionFactory sc = cfg.buildSessionFactory(new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()).build());
			return sc;
		} catch (Throwable ex) {
			// Make sure you log the exception, as it might be swallowed
			System.err.println("Initial SessionFactory creation failed." + ex);
			throw new ExceptionInInitializerError(ex);
		}
	}

	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}
}
在这里需要注意的一个地方。Hibernate3的几的版本和之后的版本创建SessionFactory的方法是不一样的。SessionFactory就是一个session的工厂,session就是与数据库的回话。

这里我们的配置已经完成了。

测试一下:

package com.smile.hibernate.test;

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

import com.smile.hibernate.model.Student;
import com.smile.hibernate.util.HibernateUtil;

public class TestHibernate {
	public static void main(String[] args) {
		SessionFactory sf = HibernateUtil.getSessionFactory();
		Session session = sf.getCurrentSession();
		session.beginTransaction();
		Student s = new Student();
		s.setId(0);
		s.setName("smile");
		s.setSex("m");
		s.setAge(25);
		session.save(s);
		session.getTransaction().commit();
//		session.close();
		sf.close();
	}
}
就可以直接将数据存到数据库中。实现了对象与关系的映射。

也可以使用Annotation的方式进行映射,就可以省去xml的映射:

package com.smile.hibernate.model;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Student {
	private int id;
	private String name;
	private String sex;
	private int age;
	@Id
	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 String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}

}

只需要两个注解就可以。

相应的将配置文件里边的关于mapping的配置修改为:

<mapping class="com.smile.hibernate.model.Student"/>




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值