论坛首页 入门技术论坛

在Eclipse下实践Struts+Hibernate 一

浏览 1409 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2008-09-26  
一、开发环境:
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
这是个配置文件,里面包含了我们所要链接数据库的一些信息,例如用户名、密码之类的东东,内容如下:
<?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">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">
            org.gjt.mm.mysql.Driver
        </property>
        <property name="hibernate.connection.url">
            jdbc:mysql://localhost/test
        </property>
        <property name="hibernate.connection.username">test</property>
        <property name="hibernate.connection.password">test</property>
        <property name="hibernate.dialect">
            org.hibernate.dialect.MySQL5Dialect
        </property>
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.transaction.factory_class">
            org.hibernate.transaction.JDBCTransactionFactory
        </property>
        <mapping   resource="com/yeepal/test/Customer.hbm.xml"/>
    </session-factory>
</hibernate-configuration>


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

3、Customer.hbm.xml
路径:src\com\yeepal\test
这个文件要和相应的类(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="com.yeepal.test.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" />
    <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、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("utyphoon@126.com");

        session.save(customer);

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

}


7、修改struts.xml
添加一个Action,全文内容如下:
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
        "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
    <include file="struts-default.xml" />

    <package name="default" extends="struts-default">
        <action name="hello"
            class="com.yeepal.test.HelloAction">
            <result name="success">success.jsp</result>
            <result name="input">index.jsp</result>
        </action>
       
        <action name="commonexample"
            class="com.yeepal.test.CommonExample">
            <result name="success">success.jsp</result>
            <result name="input">index.jsp</result>
        </action>

    </package>
</struts>


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

8、commonexample.jsp
要有点展示吧,所以就写了个超级简单的页面,只有一个按钮,什么都没有,内容如下:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="commonexample.action" method="post">
<p><input type="submit" value="提交" /></p>
</form>
</body>
</html>


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

10、下载
这里可以下载到本文代码。
论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics