在Eclipse下实践Struts+Hibernate 一

阅读更多
一、开发环境:
1、java version "1.6.0_07" [jdk-6u7-windows-i586-p.exe]
2、Eclipse Platform Version: 3.3.2 Build id: M20080221-1800 [eclipse-jee-europa-winter-win32.zip]
3、apache-tomcat-5.5.26

二、开发过程:
这是例子是延续《在Eclipse下实践Struts(不用Struts IDE).二》的基础上开发的。
1、创建数据表
     数据库就用test吧,建表:
CREATE TABLE IF NOT EXISTS `customers` (
`ID` bigint(20) NOT NULL,
`NAME` varchar(15) NOT NULL,
`EMAIL` varchar(128) NOT NULL,
`PASSWORD` varchar(8) default NULL,
`PHONE` int(11) default NULL,
`ADDRESS` varchar(255) default NULL,
`SEX` char(1) default NULL,
`IS_MARRIED` bit(1) default NULL,
`DESCRIPTION` text,
`IMAGE` blob,
`BIRTHDAY` date default NULL,
`REGISTERED_TIME` timestamp NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
PRIMARY KEY (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;


(嘿嘿,这个是网上抄来的语句,这个不是重点,就不多说了)

2、hibernate.cfg.xml
路径src\hibernate.cfg.xml
这是个配置文件,里面包含了我们所要链接数据库的一些信息,例如用户名、密码之类的东东,内容如下:



    
        
            org.gjt.mm.mysql.Driver
        
        
            jdbc:mysql://localhost/test
        
        test
        test
        
            org.hibernate.dialect.MySQL5Dialect
        
        true
        
            org.hibernate.transaction.JDBCTransactionFactory
        
        
    


其中的mapping一段,表示我们需要连接的一个表,这个配置文件我们马上就会遇到了,就是比较奇怪的是,如果这个项目用到100张表的话,这里不是要写100行,我的妈呀,代码泛滥呀。应该有更好的解决方案,后面再研究。

3、Customer.hbm.xml
路径:src\com\yeepal\test
这个文件要和相应的类(Customer.java)放在一起,内容如下:



    
      
    
    
    
    
    
    
    
         
         
    
    
    



4、Customer.java
这个文件是ORM对应的类,内容如下:
package com.yeepal.test;

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 int a;

    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;
    }

}


很长很长的内容吧,其实这里的内容,和之前Customer.hbm.xml里的内容是一一对应的,在实际项目中完全可以抄过来该改改改就OK了,敲那么多代码,想当神仙呀。

5、useHibernate.java
这个类用于启动Hibernate,内容如下:
package com.yeepal.test;

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

public class useHibernate {
    public static SessionFactory sessionFactory;

    // 初始化Hibernate,创建SessionFactory实例
    public void saveCustomer(Customer customer) throws Exception {
        Configuration config = null;
        config = new Configuration().configure();
        // 创建一个SessionFactory 实例
        sessionFactory = config.buildSessionFactory();
        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;
        } finally {
            session.close();
        }
    }
}



这里的很多内容都是通用的,也就是说在实际项目中是完全可以抄过去用的。

6、CommonExample.java
由于我是想继续之前的实验(《在Eclipse下实践Struts(不用Struts IDE).二》)继续往下做,所以这里要写一个Action,内容如下:
package com.yeepal.test;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import com.opensymphony.xwork2.ActionSupport;

public class CommonExample extends ActionSupport {

    /**
    *
    */
    private static final long serialVersionUID = 1L;
    Configuration cfg = new Configuration().configure();
    SessionFactory sessions = cfg.buildSessionFactory();
    Session session = sessions.openSession();
    Transaction tx = session.beginTransaction();

    Customer customer = new Customer();

    public String execute() throws Exception {
        customer.setName("phengchen");
        customer.setEmail("[email protected]");

        session.save(customer);

        tx.commit();
        session.close();
        return SUCCESS;
    }

}


7、修改struts.xml
添加一个Action,全文内容如下:


    

    
        
            success.jsp
            index.jsp
        
       
        
            success.jsp
            index.jsp
        

    


注意第二个action,我给他命个了名子叫commonexample,对应的类就是我们之前写的那个com.yeepal.test.CommonExample

8、commonexample.jsp
要有点展示吧,所以就写了个超级简单的页面,只有一个按钮,什么都没有,内容如下:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>




Insert title here




9、运行
前面的代码写完之后,部署起来,然后启动Tomcat,访问http://localhost:8080/cooltest/commonexample.jsp页面,可以看到只有一个按钮,点击这个按钮后,检查数据库,可以看到customers表里面多了一条记录。

10、下载
在 这里可以下载到本文代码。

你可能感兴趣的:(Hibernate,Eclipse,Struts,Windows,Phone,JSP)