第二十一部分_Hibernate深入详解

接下来我们开始介绍Hibernate的数据类型,因为我们现在暂时只关注Hibernate这块,因此我们这次只建立一个Java Project,命名为hibernate2。

加入hibernate JAR包:

选择hibernate2项目,点击MyEclipse->Add Hibernate Capabilities, Hibernate Specification与风中页老师的相同,为Hibernate3.2,点击next,继续next,去掉Specify database connection details前面的√接着next,去掉Create SessionFactory class?前面的√点击Finish。

把上一个hibernate项目的hibernate.cfg.xml文件拷贝过来,覆盖掉当前src下面的hibernate.cfg.xml文件,修改mapping信息:

<?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="show_sql">true</property> <!-- 属性之间没有上下关系,放在哪里都行 -->

    	<property name="connection.url">jdbc:mysql://localhost:3306/myhibernate</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="dialect">org.hibernate.dialect.MySQLDialect</property>

   		<mapping resource="Customers.hbm.xml"/> <!-- 将主配置文件包含对象-关系映射文件,之所以映射是因为hibernate启动时只会加载主配置文件 -->

    </session-factory>

</hibernate-configuration>

添加MySql驱动,从hibernate项目拷贝mysql-connector-java-5.1.34-bin.jar到hibernate根目录下。

创建表:(bigint即long类型;bit即boolean类型;timestamp也是一个日期类型的,比date精度更高,可以精确到毫秒;blob即二进制大型物件)

mysql> create table CUSTOMERS(
    -> ID bigint not null primary key,
    -> NAME varchar(15) not null,
    -> EMAIL varchar(128) not null,
    -> PASSWORD varchar(8) not null,
    -> PHONE int,
    -> ADDRESS varchar(255),
    -> SEX char(1),
    -> IS_MARRIED bit,
    -> DESCRIPTION text,
    -> IMAGE blob,
    -> BIRTHDAY date,
    -> REGISTERED_TIME timestamp
    -> );

新建com.test.bean包,在该包下面新建一个类Customer.java:

package com.test.bean;

import java.sql.Date;
import java.sql.Timestamp;

public class Customer
{
	private Long id;

	private String name;

	private String email;

	private String password;

	private int phone; // or Integer

	private String address;

	private char sex;

	private boolean married;

	private String description;

	private byte[] image;

	private Date birthday;

	private Timestamp registeredTime;

	public Long getId()
	{
		return id;
	}

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

	public String getName()
	{
		return name;
	}

	public void setName(String name)
	{
		this.name = name;
	}

	public String getEmail()
	{
		return email;
	}

	public void setEmail(String email)
	{
		this.email = email;
	}

	public String getPassword()
	{
		return password;
	}

	public void setPassword(String password)
	{
		this.password = password;
	}

	public int getPhone()
	{
		return phone;
	}

	public void setPhone(int phone)
	{
		this.phone = phone;
	}

	public String getAddress()
	{
		return address;
	}

	public void setAddress(String address)
	{
		this.address = address;
	}

	public char getSex()
	{
		return sex;
	}

	public void setSex(char sex)
	{
		this.sex = sex;
	}

	public boolean isMarried()
	{
		return married;
	}

	public void setMarried(boolean married)
	{
		this.married = married;
	}

	public String getDescription()
	{
		return description;
	}

	public void setDescription(String description)
	{
		this.description = description;
	}

	public byte[] getImage()
	{
		return image;
	}

	public void setImage(byte[] image)
	{
		this.image = image;
	}

	public Date getBirthday()
	{
		return birthday;
	}

	public void setBirthday(Date birthday)
	{
		this.birthday = birthday;
	}

	public Timestamp getRegisteredTime()
	{
		return registeredTime;
	}

	public void setRegisteredTime(Timestamp registeredTime)
	{
		this.registeredTime = registeredTime;
	}

}

在src下面新建一个Customers.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">

<hibernate-mapping>

	<class name="com.test.bean.Customer" table="customers"> <!-- 将类与表相关联,使得类中的属性和表中的字段关联起来 -->

		<id name="id" column="id" type="long"> <!-- 类中id属性和映射到表中的id字段,类型为int/integer皆可 -->
			<generator class="increment"> <!-- 主键id的生成方式为自增 -->
			</generator>
		</id>

		<property name="name" column="name" type="string" not-null="true"></property> <!-- 如果不写字段名,则默认与类中的属性名相同 ;hibernate层和数据库层都可以对非空进行检查-->
		<property name="email" column="email" type="string" not-null="true"></property>
		<property name="password" column="password" type="string" not-null="true"></property>
		<property name="phone" column="phone" type="int"></property>
		<property name="address" column="address" type="string" ></property>
		<property name="sex" column="sex" type="character" ></property>
		<property name="married" column="is_married" type="boolean" ></property>
		<property name="description" column="description" type="text"></property>
		<property name="image" column="image" type="binary" ></property>
		<property name="birthday" column="birthday" type="date" ></property>
		<property name="registeredTime" column="registered_time" type="timestamp"></property>

	</class>

</hibernate-mapping>

在com.test.bean包下面,创建测试类HibernateTest.java同时放置一个photo.gif文件:

package com.test.bean;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.sql.Date;
import java.util.Iterator;
import java.util.List;

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

public class HibernateTest
{
	public static SessionFactory sessionFactory;

	static
	{
		try
		{
			Configuration config = new Configuration().configure();

			sessionFactory = config.buildSessionFactory();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	public void findAllCustomers(PrintStream out) throws Exception
	{
		// Ask for a session using the JDBC information we‘ve configured
		Session session = sessionFactory.openSession();
		Transaction tx = null;
		try
		{
			tx = session.beginTransaction();
			List customers = session.createQuery("from Customer as c order by c.name asc").list();
			for (Iterator it = customers.iterator(); it.hasNext();)
			{
				printCustomer(out, (Customer) it.next());
			}

			// We‘re done; make our changes permanent
			tx.commit();

		}
		catch (Exception e)
		{
			if (tx != null)
			{
				// Something went wrong; discard all partial changes
				tx.rollback();
			}
			throw e;
		}
		finally
		{
			// No matter what, close the session
			session.close();
		}
	}

	public static void saveCustomer(Customer customer) throws Exception
	{

		// Ask for a session using the JDBC information we‘ve configured
		Session session = sessionFactory.openSession();
		Transaction tx = null;

		try
		{
			tx = session.beginTransaction();
			session.save(customer);
			// We‘re done; make our changes permanent
			tx.commit();

		}
		catch (Exception e)
		{
			if (tx != null)
			{
				// Something went wrong; discard all partial changes
				tx.rollback();
			}
			throw e;
		}
		finally
		{
			// No matter what, close the session
			session.close();
		}
	}

	public void loadAndUpdateCustomer(Long customer_id, String address)
			throws Exception
	{
		// Ask for a session using the JDBC information we‘ve configured
		Session session = sessionFactory.openSession();
		Transaction tx = null;
		try
		{
			tx = session.beginTransaction();

			Customer c = (Customer) session.load(Customer.class, customer_id);

			c.setAddress(address);

			// We‘re done; make our changes permanent

			tx.commit();

		}
		catch (Exception e)
		{
			if (tx != null)
			{
				// Something went wrong; discard all partial changes
				tx.rollback();
			}
			throw e;
		}
		finally
		{
			// No matter what, close the session
			session.close();
		}
	}

	public void deleteAllCustomers() throws Exception
	{
		// Ask for a session using the JDBC information we‘ve configured
		Session session = sessionFactory.openSession();
		Transaction tx = null;
		try
		{
			tx = session.beginTransaction();

			Query query = session.createQuery("from Customer");

			List list = query.list();

			for (Iterator i = list.iterator(); i.hasNext();)
			{
				session.delete((Customer) i.next());
			}

			tx.commit();

		}
		catch (Exception e)
		{
			if (tx != null)
			{
				// Something went wrong; discard all partial changes
				tx.rollback();
			}
			throw e;
		}
		finally
		{
			// No matter what, close the session
			session.close();
		}
	}

	private void printCustomer(PrintStream out, Customer customer)
			throws Exception
	{

		byte[] buffer = customer.getImage();
		OutputStream fout = new FileOutputStream("photo_copy.gif");
		fout.write(buffer);
		fout.close();

		out.println("------以下是" + customer.getName() + "的个人信息------");
		out.println("ID: " + customer.getId());
		out.println("口令: " + customer.getPassword());
		out.println("E-Mail: " + customer.getEmail());
		out.println("电话: " + customer.getPhone());
		out.println("地址: " + customer.getAddress());
		String sex = customer.getSex() == ‘M‘ ? "男" : "女";
		out.println("性别: " + sex);
		String marriedStatus = customer.isMarried() ? "已婚" : "未婚";
		out.println("婚姻状况: " + marriedStatus);
		out.println("生日: " + customer.getBirthday());
		out.println("注册时间: " + customer.getRegisteredTime());
		out.println("自我介绍: " + customer.getDescription());

	}

	public void test(PrintStream out) throws Exception
	{

		Customer customer = new Customer();

		customer.setName("zhangsan");
		customer.setEmail("[email protected]");
		customer.setPassword("1234");
		customer.setPhone(1381234);
		customer.setAddress("Shanghai");
		customer.setSex(‘M‘);
		customer.setDescription("I am very honest.");

		InputStream in = this.getClass().getResourceAsStream("photo.gif");

		byte[] buffer = new byte[in.available()];

		in.read(buffer);

		customer.setImage(buffer);

		customer.setBirthday(Date.valueOf("1980-05-06"));

		saveCustomer(customer);

		findAllCustomers(out);

		loadAndUpdateCustomer(customer.getId(), "Tianjin");

		findAllCustomers(out);

		deleteAllCustomers();
	}

	public static void main(String args[]) throws Exception
	{
		new HibernateTest().test(System.out);
		sessionFactory.close();
	}

}

通过给一下几行代码添加注释的方式进行测试:

		saveCustomer(customer);

		findAllCustomers(out);

		loadAndUpdateCustomer(customer.getId(), "Tianjin");

		findAllCustomers(out);

		deleteAllCustomers();

运行后在hibernate2根目录下面会生成一个photo_copy.gif图形文件。

上面的例子比较简单,下面我们看一个复杂的:表与表之间存在关联关系,类与类之间存在关联关系:

时间: 2024-11-10 01:10:17

第二十一部分_Hibernate深入详解的相关文章

zabbix专题:第二章 zabbix3.0安装详解

zabbix3.0安装详解 本节目录大纲 安装配置mariadb 安装服务器端 zabbix web配置 web页面初始化 更改为中文 中文乱码问题 zabbix专题:第二章 zabbix3.2安装详解 zabbix专题:第二章 zabbix3.2安装详解 官方文档地址: https://www.zabbix.com/documentation/3.2/manual/installation/install_from_packages 我安装zabbix用的rpm包,可以从官网的源里面去下载,需

“全栈2019”Java第二十八章:数组详解(上篇)

难度 初级 学习时间 10分钟 适合人群 零基础 开发语言 Java 开发环境 JDK v11 IntelliJ IDEA v2018.3 文章原文链接 "全栈2019"Java第二十八章:数组详解(上篇) 下一章 "全栈2019"Java第二十九章:数组详解(中篇) 学习小组 加入同步学习小组,共同交流与进步. 方式一:关注头条号Gorhaf,私信"Java学习小组". 方式二:关注公众号Gorhaf,回复"Java学习小组"

第十一章、super()详解

目录 第十一章.super()详解 一.引出super()来由 第十一章.super()详解 一.引出super()来由 原始用法: 在python类的方法中,要调用父类的某个方法,通常是类.方法() 使用非绑定的类方法(用类名来引用的方法),并在参数列表引入待绑定的对象self,达到调用父类方法的目的. 缺点: 这样做的缺点是,当一个子类的父类发生变化时(如类B的父类由A变为C时),必须遍历整个类定义,把所有的通过非绑定的方法的类名全部替换过来 如果代码简单,这样的改动或许还可以接受.但如果代

分享软件设计师教程第二三四版本+真题详解+其他考试资料下载

软件设计师教程+真题详解+其他考试资料,教程有第二版第三版第四版,带完整目录. 下载地址:网盘下载 原文地址:https://www.cnblogs.com/milugogo/p/12243121.html

linux架构学习第二十四天-DNS详解及bind搭建各种DNS测试

内容: 一.DNS 1.域名系统概述 2.域名的结构 3.域名服务器 4.域名解析过程 5.域名服务器的资源记录(resource record RR) 二.bind搭建DNS服务器 1.bind的安装 2.搭建DNS服务器 3.搭建主从DNS服务器 4.实现DNS子域 5.实现DNS视图view(智能DNS) 一.DNS 1.域名系统概述 域名系统DNS(Domain Name System)是因特网使用的命名系统,用来把便于人们使用的机器名字转换成为IP地址.域名系统其实就是名字系统.为什么

第三十一课:JSDeferred详解2

这一课,我们先接着上一课讲一下wait方法,以及wait方法是如何从静态方法变化实例方法的. 首先我们先看wait方法为啥可以从静态方法变成实例方法,请看register源码: Deferred.register= function(name, fun){  //name="wait",fun=Deferred.wait: this.prototype[name] = function(){   //this=Deferred,this.prototype[name]  = Defer

Linux常用命令(二十一) - find之参数详解

一.使用name选项: 文件名选项是find命令最常用的选项,要么单独使用该选项,要么和其他选项一起使用.  可以使用某种文件名模式来匹配文件,记住要用引号将文件名模式引起来.  不管当前路径是什么,如果想要在自己的根目录$HOME中查找文件名符合*.log的文件,使用~作为 'pathname'参数,波浪号~代表了你的$HOME目录. find ~ -name "*.log" -print 想要在当前目录及子目录中查找所有的' *.log'文件,可以用: find . -name &

Spark入门到精通--(第二节)Scala编程详解基础语法

Scala是什么? Scala是以实现scaleable language为初衷设计出来的一门语言.官方中,称它是object-oriented language和functional language的混合式语言. Scala可以和java程序无缝拼接,因为scala文件编译后也是成为.class文件,并且在JVM上运行. Spark是由Scala进行开发的. Scala安装? 这里就讲一下Scala在Centos上进行安装的过程,和安装JDK差不多. 官网下载Scala:http://www

Python第二天-list基本功能详解

1.list的定义方法 arr=["abc","def","ghi"] 2.append方法--向列表尾部追加元素 arr=["abc","def","ghi"] arr.append("jkl") print(arr); 结果为:['abc', 'def', 'ghi', 'jkl'] 3.clear方法-清除列表中的所有数据 arr=["abc"