码迷,mamicode.com
首页 > Web开发 > 详细

第二十一部分_Hibernate深入详解

时间:2015-09-24 12:52:03      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:

接下来我们开始介绍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("zhangsan@yahoo.com");
		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图形文件。

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

第二十一部分_Hibernate深入详解

标签:

原文地址:http://www.cnblogs.com/Code-Rush/p/4833595.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!