Hibernate 初步

本文将介绍使用Hibernate进行数据库操作的基本步骤,包括配置文件编写、实体类设计、映射文件创建以及核心方法使用。通过示例代码演示如何进行创建、读取、更新和删除操作。

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

hibernate-release-4.1.6: 

http://downloads.sourceforge.net/project/hibernate/hibernate4/4.1.6.Final/hibernate-release-4.1.6.Final.zip?r=http%3A//sourceforge.net%2Fprojects%2Fhibernate%2Ffiles%2Fhibernate4%2F4.1.6.Final%2F&ts=1345636454&use_mirror=nchc


Hibernate configuration file

Hibernate配置文件: hibernate.cfg.xml

property:

connection.driver_class

connection.url

connection.username

connection.password

connection.pool_size : Hibernate内置连接池,不作为生产之用。

dialect

hbm2ddl.auto : ddl自动建表之用。

mapping:

resource : mapping file的路径。例: org/hibernate/tutorial/hbm/Event.hbm.xml


<?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://127.0.0.1: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.H2Dialect</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">create</property>
        <mapping resource="org/hibernate/tutorial/hbm/Event.hbm.xml"/>
    </session-factory>
</hibernate-configuration>


Entity Java Class

实体Java类

JavaBean风格的类: getter, setter, 无参数constructor


Mapping File

EntityClassName.hbm.xml。例: Event.hbm.xml

class <-> table

id -> column : 定义主键。

property -> type, column : 这里的type是 Hibernate mapping types,用于转换Java类型和SQL类型。如果没写type,根据Java class的类型而定。


<?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="org.hibernate.tutorial.hbm">
    <class name="Event" table="EVENTS">
        <id name="id" column="EVENT_ID">
            <generator class="increment"/>
        </id>
        <property name="date" type="timestamp" column="EVENT_DATE"/>
        <property name="title"/>
    </class>
</hibernate-mapping>

示例代码:

package org.hibernate.tutorial.hbm;

import java.util.Date;

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

public class HelloHibernate {

	private SessionFactory sessionFactory;

	public HelloHibernate() {
		init();
	}

	@SuppressWarnings("deprecation")
	private void init() {
		sessionFactory = new Configuration().configure()
				.buildSessionFactory();
	}

	public void close() {
		sessionFactory.close();
	}

	public void create() {
		Session session = sessionFactory.openSession();
		Transaction transaction = session.beginTransaction();

		// Create
		session.save(new Event("hello world1", new Date())); // id=1
		session.save(new Event("hello world2", new Date())); // id=2
		session.save(new Event("hello world3", new Date())); // id=3

		transaction.commit();
		session.close();
	}

	public void read() {
		Session session = sessionFactory.openSession();
		Transaction transaction = session.beginTransaction();

		// Read
		Event e = (Event) session.get(Event.class, 1L); // id=1
		if (e != null) {
			System.out.println("event 1 : " + e.getTitle() + " " + e.getDate());
		}

		transaction.commit();
		session.close();
	}

	public void update() {
		Session session = sessionFactory.openSession();
		Transaction transaction = session.beginTransaction();

		// Update
		Event e = new Event();
		e.setId(2L);
		e.setTitle("updated");
		session.saveOrUpdate(e);

		transaction.commit();
		session.close();
	}

	public void delete() {
		Session session = sessionFactory.openSession();
		Transaction transaction = session.beginTransaction();

		// Delete
		Event e = new Event();
		e.setId(3L); // works
		session.delete(e);
		// we *always* assume an instance with a null identifier or no
		// identifier property is unsaved!
		// Event e2 = new Event();
		// e2.setTitle("hello world"); //does not work. : isTransient
		// session.delete(e2);

		transaction.commit();
		session.close();
	}

	public static void main(String[] args) {
		HelloHibernate hello = new HelloHibernate();

		hello.create();
		hello.read();
		hello.update();
		hello.delete();

		hello.close();
	}
}

Event:

package org.hibernate.tutorial.hbm;

import java.util.Date;

public class Event {
	private Long id;
	private String title;
	private Date date;

	public Event() {
		// this form used by Hibernate
	}

	public Event(String title, Date date) {
		// for application use, to create new events
		this.title = title;
		this.date = date;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public Date getDate() {
		return date;
	}

	public void setDate(Date date) {
		this.date = date;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}
}

项目目录:




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值