准备工作:
1.下载hibernate-2.1.7c.zip(目前最高版本3.05):
http://jaist.dl.sourceforge.net/sourceforge/hibernate/hibernate-2.1.7c.zip
2.下载JSQDriver:
hibernate在配置文件中明确说明“Microsoft Driver (not recommended!)”,因此先使用JSQL Driver JDBC3.0只能在JDK1.4及以上版本中使用, JBuilder 2005默认的是JDK1.43.新建函数库:
-
新建hibernate-2.1.7c库:打开JB2005,,选择菜单Tools->Configure->Libraries->New输入:hibernate-2.1.7c,点击Add按钮,将hibernate-2.1.7c.zip解压目录中的hibernate2.jar与lib/*.jar加到hibernate-2.1.7c 库中
-
-
新建JSQL库:把JSQLSetup.exe安装目录下的JDBC-3.0-Driver/JSQConnect.jar加到JSQL库中
项目步骤:
1.新建项目名:HelloApp
2.设置项目属性:
- 设置Resource :菜单Project -> Project Properties -> Build ->Resource 里选xml文件,选择“Copy” --在编译该项目的时候,会自动将src文件夹里的xml文件拷贝到classes文件夹里的相应目录下
- 设置Required Libraries:菜单Project -> Project Properties ->Path/Required Libraries,把Hiberate与JSQL库添加进来,--在编译该项目的时候,会自动将库文件的jar包l拷贝到lib文件夹中
3. 新建Web模块,选菜单File->New->Web->WebMoldule,取名为webApp
4.用servlet向导新建一个servlet文件,选菜单File->New,在弹出的对话框中选择Web->Standard Servlet,取名为DBServlet,代码如下:
package mypack;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;public class DBServlet extends HttpServlet {
public void init(ServletConfig config)
throws ServletException {
super.init(config);
}public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {// If it is a get request forward to doPost()
doPost(request, response);}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
try{
response.setContentType("text/html;charset=GB2312");
new BusinessService().test(this.getServletContext(),response.getOutputStream());
}catch(Exception e){e.printStackTrace();
}
}public void destroy() {
}
}5.创建一个持久化类Customer .java
5.创建一个持久化类Customer .javapackage mypack;
import java.io.Serializable;
import java.sql.Date;
import java.sql.Timestamp;public class Customer implements Serializable {
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;
}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 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;
}}
6.创建通过HibernateAPI操纵数据库BusinessService.java
6.创建通过HibernateAPI操纵数据库BusinessService.javapackage mypack;
import javax.servlet.*;
import net.sf.hibernate.*;
import net.sf.hibernate.cfg.Configuration;
import java.io.*;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.*;public class BusinessService{
public static SessionFactory sessionFactory;
static{
try{
// Create a configuration based on the properties file we've put
// in the standard place.
Configuration config = new Configuration();
config.addClass(Customer.class);
// Get the session factory we can use for persistence
sessionFactory = config.buildSessionFactory();
}catch(Exception e){e.printStackTrace();}
}public void findAllCustomers(ServletContext context,OutputStream 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.find("from Customer as c order by c.name asc");
for (Iterator it = customers.iterator(); it.hasNext();) {
printCustomer(context,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 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();
session.delete("from Customer as c");
// 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();
}
}private void printCustomer(ServletContext context,OutputStream out,Customer customer)throws Exception{
if(out instanceof ServletOutputStream)
printCustomer(context,(ServletOutputStream) out,customer);
else
printCustomer((PrintStream) out,customer);
}
private void printCustomer(PrintStream out,Customer customer)throws Exception{
//save photo
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());}
private void printCustomer(ServletContext context,ServletOutputStream out,Customer customer)throws Exception{
//save photo
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,OutputStream 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.");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(context,out);
loadAndUpdateCustomer(customer.getId(),"Beijing");
findAllCustomers(context,out);deleteAllCustomers();
}public static void main(String args[]) throws Exception {
new BusinessService().test(null,System.out);
sessionFactory.close();
}}
7.创建表示层Hello.jsp
7.创建表示层Hello.jsp<html locale="true">
<head>
<title>hello.jsp</title>
</head>
<body bgcolor="white">
<jsp:forward page="DBServlet" />
</body>
</html>8.创建Hibernate配置文件hibernate.properties(此文件放在src目录中):
## MS SQL Serverhibernate.dialect net.sf.hibernate.dialect.SQLServerDialect
hibernate.connection.username sa
hibernate.connection.password sa## JSQL Driver
hibernate.connection.driver_class com.jnetdirect.jsql.JSQLDriver
hibernate.connection.url jdbc:JSQLConnect://sun/test这段说明:我们使用的数据库服务器机器名为sun,数据库名为test,连接到数据库上去的用户名为sa,密码为sa
9.创建对象-关系映射文件Customer.hbm.xml(此文件与Customer.java放在同一目录中):
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 2.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.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>
10.copylog4j.properties文件放在src目录中(此文件在hibernate-2.1/etc目录下)
数据库的创建: