说明

基于Hibernate 3.0,Mysql5.0,java jdk 1.7,运行需要的lib 库,从http://files.cnblogs.com/HCCZX/Hibernate_Lib.rar  下载。
下面开始一步步写代码

1.创建数据库

drop database if exists SAMPLEDB;
create database SAMPLEDB;
use SAMPLEDB; 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
);

2.添加java  VO 对象,也叫 pojo,javabean,不知为啥这么多个叫法。

package mypack;

import java.io.Serializable;
import java.sql.Date;
import java.sql.Timestamp; public class Customer implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String name;
private String email;
private String password;
private int phone;
private String address;
private char sex;
private boolean married;
private String description;
private byte[] image;
private Date birthday;
private Timestamp registeredTime; public Customer() {
} public Long getId() {
return id;
} @SuppressWarnings("unused")
private 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 this.image;
} public void setImage(byte[] image) {
this.image = image;
} public Date getBirthday() {
return this.birthday;
} public void setBirthday(Date birthday) {
this.birthday = birthday;
} public Timestamp getRegisteredTime() {
return this.registeredTime;
} public void setRegisteredTime(Timestamp registeredTime) {
this.registeredTime = registeredTime;
} }

3.添加Hibernate 对象关系映射文件

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping>
<class name="mypack.Customer" table="CUSTOMERS"> <id name="id" column="ID" type="long">
<generator class="increment"/>
</id>
<property name="name" column="NAME" type="string" not-null="true" />
<property name="email" column="EMAIL" type="string" not-null="true" />
<property name="password" column="PASSWORD" type="string" not-null="true"/>
<property name="phone" column="PHONE" type="int" />
<property name="address" column="ADDRESS" type="string" />
<property name="sex" column="SEX" type="character"/>
<property name="married" column="IS_MARRIED" type="boolean"/>
<property name="description" column="DESCRIPTION" type="text"/>
<property name="image" column="IMAGE" type="binary"/>
<property name="birthday" column="BIRTHDAY" type="date"/>
<property name="registeredTime" column="REGISTERED_TIME" type="timestamp"/> </class> </hibernate-mapping>

4.添加Hibernate  配置文件 hibernate.properties

hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.connection.driver_class=com.mysql.jdbc.Driver
hibernate.connection.url=jdbc:mysql://localhost:3306/SAMPLEDB
hibernate.connection.username=root
hibernate.connection.password=aaaaaa
hibernate.show_sql=true

5.添加底层操作代码

package mypack;

import javax.servlet.*;

import org.hibernate.*;
import org.hibernate.cfg.Configuration; import java.io.*;
import java.sql.Date;
import java.util.*; public class BusinessService{
public static SessionFactory sessionFactory; /** 初始化Hibernate,创建SessionFactory实例 */
static{
try{
// 根据默认位置的Hibernate配置文件的配置信息,创建一个Configuration实例
Configuration config = new Configuration();
//加载Customer类的对象-关系映射文件
config.addClass(Customer.class);
// 创建SessionFactory实例 */
sessionFactory = config.buildSessionFactory();
}catch(RuntimeException e){e.printStackTrace();throw e;}
} /** 查询所有的Customer对象,然后调用printCustomer()方法打印Customer对象信息 */
public void findAllCustomers(ServletContext context,PrintWriter out) 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");
@SuppressWarnings("unchecked")
List<Customer> customers=query.list();
for (Iterator<Customer> it = customers.iterator(); it.hasNext();) {
printCustomer(context,out,it.next());
} tx.commit(); //提交事务 }catch (RuntimeException e) {
if (tx != null) {
tx.rollback();
}
throw e;
} finally {
session.close();
}
} /** 持久化一个Customer对象 */
public void saveCustomer(Customer customer){
Session session = sessionFactory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
session.save(customer);
tx.commit(); }catch (RuntimeException e) {
if (tx != null) {
tx.rollback();
}
throw e;
} finally {
session.close();
}
} /** 按照OID加载一个Customer对象,然后修改它的属性 */
public void loadAndUpdateCustomer(Long customer_id,String address){
Session session = sessionFactory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction(); Customer c=(Customer)session.get(Customer.class,customer_id);
c.setAddress(address);
tx.commit(); }catch (RuntimeException e) {
if (tx != null) {
tx.rollback();
}
throw e;
} finally {
session.close();
}
} /**删除Customer对象 */
public void deleteCustomer(Customer customer){
Session session = sessionFactory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
session.delete(customer);
tx.commit(); }catch (RuntimeException e) {
if (tx != null) {
tx.rollback();
}
throw e;
} finally {
session.close();
}
} /** 选择向控制台还是Web网页输出Customer对象的信息 */
private void printCustomer(ServletContext context,PrintWriter out,Customer customer)throws Exception{
if(context!=null)
printCustomerInWeb(context,out,customer);
else
printCustomer( out,customer);
} /** 把Customer对象的信息输出到控制台,如DOS 控制台*/
private void printCustomer(PrintWriter out,Customer customer)throws Exception{
byte[] buffer=customer.getImage();
FileOutputStream 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()); } /** 把Customer对象的信息输出到动态网页 */
private void printCustomerInWeb(ServletContext context,PrintWriter out,Customer customer)throws Exception{
//保存照片
byte[] buffer=customer.getImage();
String path=context.getRealPath("/");
FileOutputStream fout=new FileOutputStream(path+"photo_copy.gif");
fout.write(buffer);
fout.close(); out.println("------以下是"+customer.getName()+"的个人信息------"+"<br>");
out.println("ID: "+customer.getId()+"<br>");
out.println("口令: "+customer.getPassword()+"<br>");
out.println("E-Mail: "+customer.getEmail()+"<br>");
out.println("电话: "+customer.getPhone()+"<br>");
out.println("地址: "+customer.getAddress()+"<br>");
String sex=customer.getSex()=='M'? "男":"女";
out.println("性别: "+sex+"<br>");
String marriedStatus=customer.isMarried()? "已婚":"未婚";
out.println("婚姻状况: "+marriedStatus+"<br>");
out.println("生日: "+customer.getBirthday()+"<br>");
out.println("注册时间: "+customer.getRegisteredTime()+"<br>");
out.println("自我介绍: "+customer.getDescription()+"<br>");
out.println("<img src='photo_copy.gif' border=0><p>");
}
public void test(ServletContext context,PrintWriter out) throws Exception{ Customer customer=new Customer();
customer.setName("Tom");
customer.setEmail("tom@yahoo.com");
customer.setPassword("1234");
customer.setPhone(55556666);
customer.setAddress("Shanghai");
customer.setSex('M');
customer.setDescription("I am very honest."); //设置Customer对象的image属性,它是字节数组,存放photo.gif文件中的二进制数据
//photo.gif文件和BusinessService.class文件位于同一个目录下
InputStream in=this.getClass().getResourceAsStream("photo.gif");
byte[] buffer = new byte[in.available()];
in.read(buffer);
customer.setImage(buffer);
//设置Customer对象的birthday属性,它是java.sql.Date类型
customer.setBirthday(Date.valueOf("1980-05-06")); saveCustomer(customer); findAllCustomers(context,out);
loadAndUpdateCustomer(customer.getId(),"Beijing");
findAllCustomers(context,out);
deleteCustomer(customer);
} public static void main(String args[]) throws Exception {
new BusinessService().test(null,new PrintWriter(System.out,true));
sessionFactory.close(); }
}

Hibernate 3.0 HelloWorld的更多相关文章

  1. SpringBoot入门(0) HelloWorld的实现与原理分析

    SpringBoot(0) HelloWorld的实现与原理分析 一.环境准备 1.1 环境约束 –jdk1.8:Spring Boot 推荐jdk1.7及以上:java version “1.8.0 ...

  2. Hibernate —— 概述与 HelloWorld

    一.Hibernate 概述 1.Hibernate 是一个持久化框架 (1)从狭义的角度来讲,“持久化” 仅仅指把内存中的对象永久的保存到硬盘中的数据库中. (2)从广义的角度来讲,“持久化” 包括 ...

  3. hibernate 02之helloworld

    1.安装插件 安装方法说明(hibernatetools-.Final): Help --> Install New Software... Click Add... In dialog Add ...

  4. Hibernate学习0.Hibernate入门

    Hibernate是什么 面向java环境的对象/关系数据库映射工具. 1.开源的持久层框架. 2.ORM(Object/Relational Mapping)映射工具,建立面向对象的域模型和关系数据 ...

  5. SSH(Struts 2.3.31 + Spring 4.1.6 + Hibernate 5.0.12 + Ajax)框架整合实现简单的增删改查(包含分页,Ajax 无刷新验证该用户是否存在)

    软件152 余建强 该文将以员工.部门两表带领大家进入SSH的整合教程: 源码下载:http://download.csdn.net/detail/qq_35318576/9877235 SSH 整合 ...

  6. 小峰Hibernate简介与HelloWorld

    一.Hibernate简介: 二.Hibernate4 版Hello World 实现 工程结构: com.cy.model.Student: package com.cy.model; public ...

  7. 80. Hibernate 5.0命名策略使用naming-strategy 不起作用【从零开始学Spring Boot】

    [原创文章,转载请注明出处] 事情的起因:一不小心从1.3.3升级到了1.4.0版本,结果就碰到了各种悲催的事情了,好吧,Hibernate5.0的新特性就是其中一个坑,我们会发现我们配置的namin ...

  8. cocos2d-3.0 Helloworld::onTouchMoved的处理机制的推測

    bool sign2 = true; bool sign2 = true; void GameLayer::onTouchMoved(Touch *touch, Event *unused){ if( ...

  9. hibernate-mapping-3.0.dtd;hibernate-configuration-3.0.dtd;hibernate.properties所在路径

    hibernate-mapping-3.0.dtd 所在路径:hibernate-release-5.2.5.Final\project\hibernate-core\src\main\resourc ...

随机推荐

  1. 如何把GitHub中的开源项目导入到Eclipse

    准备: 1.需要注册GitHub的账号,并找到自己想导入的项目 2.在Eclipse的help-->Marketplace中搜索egit插件,然后安装 操作步骤: 1.有三种导入方式HTTP.S ...

  2. 9、Dubbo-配置(4)

    本地存根 远程服务后,客户端通常只剩下接口,而实现全在服务器端,但提供方有些时候想在客户端 也执行部分逻辑,比如:做 ThreadLocal 缓存,提前验证参数,调用失败后伪造容错数据等 等,此时就需 ...

  3. Kali-linux攻击路由器

    前面介绍的各种工具,都是通过直接破解密码,来连接到无线网络.由于在一个无线网络环境的所有设备中,路由器是最重要的设备之一.通常用户为了保护路由器的安全,通常会设置一个比较复杂的密码.甚至一些用户可能会 ...

  4. EF和linq to sql 关系

    LINQ to SQL 允许你用任何类来代表数据库中的数据.表.同样的,EF也允许你用任何类来代表苏据库中的数据.表. 所不同的的地方是Linq to sql 用这些被修饰过的类直接同数据库打交道,存 ...

  5. PyTorch Notes | PyTorch 编程实践笔记

    [ 今天最开心的事情! ] PyTorch的stable版本更新为1.0之后,原本3D模型无脑out of memory.3D模型torch.backends.cudnn.benchmark必须Fal ...

  6. "strace -p"非常有用,它减少了很多猜测工作,也不需要重新启动应用。lsof -p process_id +iostat + sar -n DEV 1

    linux神器strace - youxin - 博客园https://www.cnblogs.com/youxin/p/8837771.html 某个进程突然占用了很多CPU? 或者某个进程看起来像 ...

  7. Java中的IO流(五)

    上一篇<Java中的IO流(四)>记录了一下Properties类,此类不属于IO流,它属于集合框架.接下来说一下IO流中的其它流 一,打印流PrintStream PrintStream ...

  8. 20181101noip模拟赛T1

    思路: 我们看到这道题,可以一眼想到一维差分 但这样的复杂度是O(nq)的,显然会T 那么怎么优化呢? 我们会发现,差分的时候,在r~r+l-1的范围内 差分增加的值横坐标相同,纵坐标递增 减小的值横 ...

  9. 【Java web 容器resin的安装】

    #resin的安装 #启动resin #访问resin监听的java web容器端口 resin修改端口监听号

  10. 课时54.audio标签(掌握)

    1.什么是audio标签? 播放音频 格式: <audio src=""> </audio> 也是由于同样的适配问题,所以出现了第二种格式 <audi ...