Hibernate 简单的增删改查 示例

本文通过创建一个简单的Box表及其对应的Java对象,演示了如何利用Hibernate框架进行数据库操作,包括增删改查等基本功能。

创建数据库ssh下的一张表box:  

 create table `ssh`.`box`(
        `id` INT not null auto_increment,
       `width` FLOAT,
       `length` FLOAT,
       `height` FLOAT,
       `name` VARCHAR(20),
        primary key (`id`)
    );

Box.java:

package base.helloworld;
public class Box {
	private Integer id;
	private Float width;
	private Float length;
	private Float height;
	private String name;
	public Box(){}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public Float getWidth() {
		return width;
	}
	public void setWidth(Float width) {
		this.width = width;
	}
	public Float getLength() {
		return length;
	}
	public void setLength(Float length) {
		this.length = length;
	}
	public Float getHeight() {
		return height;
	}
	public void setHeight(Float height) {
		this.height = height;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}

Box.hbm.xml:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- 
	Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
	<!--指定类和对象的表-->
	<class name="base.helloworld.Box" table="box" >
		<!--指定主键-->
		<id name="id" type="java.lang.Integer">
			<column name="id" length="11"/>
			<generator class="native" />
		</id>
		<!--定义各字段-->
		<property name="width" type="java.lang.Float">
			<column name="width" precision="12" scale="0" />
		</property>
		<property name="length" type="java.lang.Float">
			<column name="length" precision="12" scale="0" />
		</property>
		<property name="height" type="java.lang.Float">
			<column name="height" precision="12" scale="0" />
		</property>
		<property name="name" type="java.lang.String">
			<column name="name" length="20" />
		</property>
	</class>
</hibernate-mapping>

注:precision="12" 表示有效位数是12位,scale="0" 表示小数位为0

hibernate.cfg.xml:

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

<session-factory>
	<property name="dialect">
		org.hibernate.dialect.MySQLDialect
	</property>
	<property name="connection.url">
		jdbc:mysql://localhost:3306/ssh
	</property>
	<property name="connection.username">root</property>
	<property name="connection.password">root</property>
	<property name="connection.driver_class">
		com.mysql.jdbc.Driver
	</property>
	<property name="myeclipse.connection.profile">MySQL5</property>
	<mapping resource="base/helloworld/Box.hbm.xml" />

</session-factory>

</hibernate-configuration>
Test.java:

package base.helloworld;

import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class Test {

	public static void main(String[] args) {
		// Configuration管理Hibernate配置
		Configuration config = new Configuration().configure();
		// 根据Configuration建立 SessionFactory
		// SessionFactory用来建立Session
		SessionFactory sessionFactory = config.buildSessionFactory();

		// 1 显示所有记录
		// 建立Session,相当于建立JDBC的Connection
		Session session = sessionFactory.openSession();
		// 查询所有记录
		List result = session.createQuery("from Box").list();
		// 显示记录
		System.out.println("数据内容:id  名称   长度  宽度  高度");
		for (int i = 0; i < result.size(); i++) {
			Box box = (Box) result.get(i);
			System.out.println("       " + box.getId() + " " + box.getName() + " "
					+ box.getLength() + " " + box.getWidth() + " "
					+ box.getHeight());
		}
		session.close();

		// 2增加记录
		Box box = new Box();
		box.setHeight(24.3f);
		box.setLength(100.00f);
		box.setWidth(45.00f);
		box.setName("My Box");
		session = sessionFactory.openSession();
		Transaction tx = session.beginTransaction();
		// 将对象保存到数据库当中,并获得id值
		Integer boxid = (Integer) session.save(box);
		tx.commit();
		session.close();
		System.out.println("id为" + boxid + "的记录已经添加!");

		// 查询添加的记录数据
		session = sessionFactory.openSession();
		tx = session.beginTransaction();
		box = (Box) session.load(Box.class, boxid); //根据给定实体类和标识返回持久化状态的实例
		System.out.println("id为" + boxid + "数据修改前:id  名称   长度  宽度  高度");
		System.out.println("                      " + box.getId() + " "
				+ box.getName() + " " + box.getLength() + " " + box.getWidth()
				+ " " + box.getHeight());
		// 3 修改对象
		box.setName("Update Box!");
		box.setWidth(35.6f);
		// 更新数据库
		session.update(box);
		// 提交事务
		tx.commit();
		// 查看更新结果
		box = (Box) session.load(Box.class, boxid);
		System.out.println("id为" + boxid + "数据修改前:id  名称   长度  宽度  高度");
		System.out.println("                      " + box.getId() + " "
				+ box.getName() + " " + box.getLength() + " " + box.getWidth()
				+ " " + box.getHeight());
		session.close();

		// 4删除记录
		session = sessionFactory.openSession();
		tx = session.beginTransaction();
		box = (Box) session.load(Box.class, boxid);
		session.delete(box);
		// 提交事务
		tx.commit();
		System.out.println("id为" + boxid + "的记录已经删除!");
		// 查看结果,如果没有记录,get返回null,如果使用load方法,则抛出异常
		box = (Box) session.get(Box.class, boxid);
		if (box == null)
			System.out.println("找不到对应的记录:" + boxid);
		session.close();

		// 关闭sessionFactory
		sessionFactory.close();

	}

}

持久化对象(Java对象)的三态:

临时状态(Transient):刚刚用new语句创建,还没有被持久化,不处于Session的缓存中。

持久化状态(Persistent):已经被持久化,加入到Session的缓存中。

游离状态(Detached):已经被持久化,但不再处于Session的缓存中。

 

 

运行结果,根据访问次数而稍变,像下图:



注:各配置文件的具体含义见MyBlog:Hibernate 第一个例子 详解



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

itzyjr

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值