關於部落格
換個方向思考反而能更真切的看出事物的真實與本質
  • 65509

    累積人氣

  • 2

    今日人氣

    0

    訂閱人氣

[AJAX][ZK][Hibernate] ZK & Hibernate


1. 開個ZK Project (Dynamic Web Project with ZK Library)

不會的話,方法可以參照官網的教學: http://www.zkoss.org/doc/studioguide/ch03s02.html

2.安裝Hibernate到專案內
基本上我是使用目前最新的,Hibernate下載網址: http://www.hibernate.org/
裡面有Download,點下去後可以下載Hibernate Core(3.3.1.GA),因為我要用Annotation,所以還要再下載Hibernate Annotations(3.4.0 GA),下載完檔案後,主要需要用到的檔如下,只要把下面這些檔放到新開專案的WEB-INF/lib內就OK囉!!

Hibernate Core
hibernate3.jar
lib/required/antlr-2.7.6.jar
lib/required/commons-collections-3.1.jar
lib/required/dom4j-1.6.1.jar
lib/required/jta-1.1.jar
lib/required/slf4j-api-1.5.2.jar
lib/required/javassist-3.4.GA.jar

Hibernate Annotations
hibernate-annotations.jar
lib/ejb3-persistence.jar
lib/hibernate-commons-annotations.jar
lib/test/log4j.jar **
lib/test/slf4j-log4j12.jar **

** 若沒有要用Annotation的話這兩個檔還是要放進去的,若沒有放的話會出現SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder"的錯誤訊息,這裡只是剛好Hibernate Annotations這裡面有可以用,要不然是需要另外下載來使用的,下載除了Log4J之外還有其他多種的選擇,這裡就不再說明了。

3.設定ZK Configuration檔
修改新專案WEB-INF下的zk.xml檔,主要要加入的設定如下,直接拷貝貼上即可,也可以看官網的:http://www.zkoss.org/doc/devguide/ch16s03.html

<!-- Hibernate SessionFactory lifecycle -->
<listener>
<description>Hibernate SessionFactory lifecycle</description>
<listener-class>org.zkoss.zkplus.hibernate.HibernateSessionFactoryListener</listener-class>
</listener>

<!-- Hibernate OpenSessionInView Pattern -->
<listener>
<description>Hibernate Open Session In View life-cycle</description>
<listener-class>org.zkoss.zkplus.hibernate.OpenSessionInViewListener</listener-class>
</listener>

<!-- Hibernate thread session context handler -->
<listener>
<description>Hibernate thread session context handler</description>
<listener-class>org.zkoss.zkplus.hibernate.HibernateSessionContextListener</listener-class>
</listener>

4.建立Java物件
這裡以通訊錄為例,我要建個Person的類別,要有的欄位有姓名、生日、電話及eMail,用Annotation的程式碼大致如下,放在src/test下,若沒有用Annotation的話,可 以參考官網,要多設定一下Mapping File:http://www.zkoss.org/doc/devguide/ch16s05s01.html

package test;

import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "person")
public class Person {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;
    private Date birthday;
    private String phone;
    private String email;

    public Person() {}

    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 Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

5.建立Hibernate Configuration檔
這裡我是用MySQL5的,至於安裝就不用說明了吧!,我的設定檔(hibernate.cfg.xml)大致如下,放到src下即可,這兒也可以參考官網,不過不是用MySQL就是了:http://www.zkoss.org/doc/devguide/ch16s06.html

<?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?useUnicode=true&amp;characterEncoding=utf-8</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password"></property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>

        <!-- Disable the second-level cache -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">create</property>
  
        <mapping class="test.Person" />
    </session-factory>
</hibernate-configuration>

因為我是用Annotation的,所以要多打個<mapping class="test.Person" />,若不是用Annotation的話就是打類似這樣<mapping resource="test/Person.hbm.xml"/>,裡面有設定像是hbm2ddl.auto,設定是會自己建資料表的,每次都會重建,所以資料都會清掉要注意一下。

6.建立個DAO物件
其實沒有用DAO也是可以直接來存取資料啦,不過若有用的話會比較方便,也更易於維護喔!參考官網:http://www.zkoss.org/doc/devguide/ch16s07.html

package test;

import java.util.Date;
import java.util.List;
import org.hibernate.Session;
import org.zkoss.zkplus.hibernate.HibernateUtil;

public class PersonDAO {
    Session currentSession() {
        return HibernateUtil.currentSession();
    }

    public void saveOrUpdate(Person aPerson, String name, Date birthday, String phone, String email) {
        Session sess = currentSession();
        aPerson.setName(name);
        aPerson.setBirthday(birthday);
        aPerson.setPhone(phone);
        aPerson.setEmail(email);
        sess.saveOrUpdate(aPerson);
    }

    public void delete(Person aPerson) {
        Session sess = currentSession();
        sess.delete(aPerson);
    }

    public Person findById(Long id) {
        Session sess = currentSession();
        return (Person) sess.load(Person.class, id);
    }

    public List findAll() {
        Session sess = currentSession();
        return sess.createQuery("from Person").list();
    }
}

7.建立ZUML Page
這裡我要用Data Binding的方式,基本上在用法上很直覺的,只要加個幾行設定就行了,程式如下存成你喜歡的檔名.zul即可,若沒有要用Data Binding的方式,則是可以參考官網的範例:http://www.zkoss.org/doc/devguide/ch16s08.html

<?page id="ContactBook" title="ContactBook" cacheable="false" language="xul/html" zscriptLanguage="Java" contentType="text/html;charset=UTF-8"?>
<?init class="org.zkoss.zkplus.databind.AnnotateDataBinderInit"?>

<zk xmlns="http://www.zkoss.org/2005/zul"
    xmlns:h="http://www.w3.org/1999/xhtml"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.zkoss.org/2005/zul http://www.zkoss.org/2005/zul/zul.xsd">
    <window title="通訊錄" border="normal" width="700px">
        <zscript><![CDATA[
        import test.Person;
        import test.PersonDAO;

        List allPersons = new PersonDAO().findAll();
  
        void insert() {
            new PersonDAO().saveOrUpdate(new Person(),name.value,birthday.value,phone.value,email.value);
            List plist = contactbook.getModel();
            plist.clear();
            plist.addAll(new PersonDAO().findAll());
        }

        void delete(Person aPerson) {
            new PersonDAO().delete(aPerson);
            List plist = contactbook.getModel();
            plist.clear();
            plist.addAll(new PersonDAO().findAll());
        }
  
        void update(Person aPerson) {
            new PersonDAO().saveOrUpdate(aPerson,name.value,birthday.value,phone.value,email.value);
        }
        ]]></zscript>
        <listbox id="contactbook" fixedLayout="true" model="@{allPersons}" selectedItem="@{selected}" >
            <listhead sizable="true">
                <listheader label="姓名" />
                <listheader label="生日" />
                <listheader label="電話" />
                <listheader label="eMail" />
            </listhead>
            <listitem self="@{each=person}">
                <listcell label="@{person.name}" />
                <listcell label="@{person.birthday}" />
                <listcell label="@{person.phone}" />
                <listcell label="@{person.email}" />
            </listitem>
        </listbox>
        <grid width="100%">
            <rows>
                <row>
                    姓名:<textbox id="name" value="@{selected.name}"/>
                    生日:<datebox id="birthday" value="@{selected.birthday}" />
                </row>
                <row>
                    電話:<textbox id="phone" value="@{selected.phone}" />
                    eMail:<textbox id="email" value="@{selected.email}" constraint="/.+@.+.[a-z]+/:請輸入正確的eMail!" />
                </row>
                <row spans="4" align="right"><hbox>
                    <button label="刪除" onClick="delete(selected)" />
                    <button label="新增" onClick="insert()" />
                    <button label="修改" onClick="update(selected)" /></hbox>
                </row>
            </rows>
        </grid>
    </window>
</zk>

就這樣,主要要注意的就是一定要放上<?init class="org.zkoss.zkplus.databind.AnnotateDataBinderInit"?>這一段,接著呢!在Eclipse用ZUL Editor的情況下,ZK Script區間的Java Code要用<![CDATA[開頭,以及]]結尾,這樣才會有顏色、程式碼檢查以及自動完成的方便功能,關於Data Binding的部份,官網也是有相關的文件可以參考:http://www.zkoss.org/doc/devguide/ch08.html

執行後就會看到,上面是一個Listbox,會列出所有的人員資料,而下面有個表單可以填資料,玩一玩,簡單吧!
相簿設定
標籤設定
相簿狀態