Hibernate 基础

建表sql

create table customers(
	id		bigint		primary key,
	name	varchar(20)	not null,
	pass	varchar(20) not null,
	email	varchar(128) not null,
	image	mediumblob,
	birthday	date,
	registered_time	timestamp
);
Customer

package org.zbq.bean;

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

public class Customer {
	private Long id;
	private String name;
	private String pass;
	private String email;
	private	byte[] image;
	private Date birthday;
	private Timestamp registeredTime;
	public Timestamp getRegisteredTime() {
		return registeredTime;
	}
	public void setRegisteredTime(Timestamp registeredTime) {
		this.registeredTime = 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 getPass() {
		return pass;
	}
	public void setPass(String pass) {
		this.pass = pass;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	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;
	}
}
Customer.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="org.zbq.bean.Customer" table="customers">
		<id name="id" type="long">
			<generator class="increment"></generator>
		</id>
		
		<property name="name" type="string" not-null="true"/>
		<property name="pass" type="string" not-null="true"/>
		<property name="email" type="string" not-null="true"></property>
		<property name="image" type="binary"></property>
		<property name="birthday" type="date"></property>
		<property name="registeredTime" column="registered_time" type="timestamp" />
		
	</class>
</hibernate-mapping>

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/Hibernate</property>
        <property name="connection.username">root</property>
        <property name="connection.password">mysqladmin</property>
        <property name="connection.driver_class">org.gjt.mm.mysql.Driver</property>
    	<property name="show_sql">true</property>
    	
    	<mapping resource="org/zbq/bean/Customer.hbm.xml"/>
    </session-factory>

</hibernate-configuration>
Test

package org.zbq.test;

import java.io.File;
import java.io.FileInputStream;
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;
import org.zbq.bean.Customer;

public class HibernateTest {
	public static SessionFactory sessionFactory;
	
	static {
		try{
			Configuration config = new Configuration().configure();
			sessionFactory = config.buildSessionFactory();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	@SuppressWarnings("unchecked")
	public static void findAll() throws Exception {
		Session session = sessionFactory.openSession();
		Transaction tx = null;
		try{
			tx = session.beginTransaction();
			Query query = session.createQuery("from Customer as c order by c.name asc");
			List<Customer> customers = query.list();
			
			for(Iterator<Customer> it = customers.iterator(); it.hasNext();){
				Customer c = it.next();
//				System.out.println(c.getName());
				printCustomer(System.out, c);
			}
			
			tx.commit();
		}catch(Exception e){
			if(tx != null){
				tx.rollback();
			}
			throw e;
		}
		
	}
	
	public static void saveCustomer(Customer customer) throws Exception{
		Session session = sessionFactory.openSession();
		Transaction tx = null;
		try{
			tx = session.beginTransaction();
			session.save(customer);
			tx.commit();
		}catch(Exception e){
			if(tx != null){
				tx.rollback();
			}
			throw e;
		}
	}
	
	public static void printCustomer(PrintStream out, Customer customer) throws Exception{
		byte[] buff = customer.getImage();
		OutputStream fout = new FileOutputStream("p_copy" + customer.getId() + ".jpg");
		fout.write(buff);
		fout.close();
		
		out.println("ID:" + customer.getId());
		out.println("Name:" + customer.getName());
		out.println("Email:" + customer.getEmail());
		out.println("Birthday:" + customer.getBirthday());
		out.println("RegisteredTime:" + customer.getRegisteredTime());
		fout.close();
	}
	
	public static void updateCustomer(long id, byte[] image) throws Exception{
		Session session = sessionFactory.openSession();
		Transaction tx = null;
		try{
			tx = session.beginTransaction();
			Customer c = (Customer) session.load(Customer.class, id);
			c.setImage(image);
			tx.commit();
		}catch (Exception e) {
			if(tx != null){
				tx.rollback();
			}
			throw e;
		}
	}
	
	@SuppressWarnings("unchecked")
	public static void deleteCustomer(long id) throws Exception{
		Session session = sessionFactory.openSession();
		Transaction tx = null;
		try{
			tx = session.beginTransaction();
			Query query = session.createQuery("from Customer");
			List<Customer> lists = query.list();
			for(Customer c : lists){
				if(c.getId() == id){
					session.delete(c);
				}
			}
			tx.commit();
		}catch (Exception e) {
			if(tx != null){
				tx.rollback();
			}
			throw e;
		}
	}
	
	public void test(PrintStream out) throws Exception{
		Customer customer = new Customer();
		
		customer.setBirthday(Date.valueOf("2013-1-12"));
		customer.setEmail("Jack@gmail.com");
		customer.setName("Jack");
		customer.setPass("pass@123");
//		customer.setRegisteredTime(registeredTime)
		
		InputStream in = new FileInputStream(new File("WebRoot/images/028.jpg"));
		
//		InputStream in = this.getClass()
//			.getResourceAsStream("003.jpg");
//		byte[] buff = new byte[in.available()];
//		in.read(buff);
		
		byte[] image = new byte[in.available()];
		in.read(image);
		customer.setImage(image);
		
		saveCustomer(customer);
//		updateCustomer(6, image);
//		findAll();
//		deleteCustomer(1);
		
		in.close();
	}
	
	
	public static void main(String[] args) throws Exception {
		new HibernateTest().test(System.out);
		File file = new File("WebRoot/images/004.jpg");
		System.out.println(file.exists());
		
//		HibernateTest t = new HibernateTest();
//		System.out.println(t.getClass().getResourceAsStream(file.getAbsolutePath()));
	}

}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值