spring3 hibernate3 架構網站

設定Spring3 環境

首先準備spring的jar檔, 下載

在Eeclipes 下新增專案後之後,請放到專案下的WebContent\WEB-INF\lib裡面去。

修改 WEB-INF/web.xml 增加以下內容。

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

因為設定了classpath:applicationContext.xml 接下來再去src底下建立一個applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="
 
http://www.springframework.org/schema/beans
 
 
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
 
 
http://www.springframework.org/schema/context
 
 
http://www.springframework.org/schema/context/spring-context-3.1.xsd
 
 
http://www.springframework.org/schema/tx
 
 
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
 
 
http://www.springframework.org/schema/aop
 
        http://www.springframework.org/schema/aop/spring-aop-3.1.xsd ">
 
    <!-- add here -->
     
</beans>

基本上 這樣子spring就建立起來了
接下來要整合hibernate

設定 Hibernate 環境

首先準備資料庫
請隨便建立個表
這裡的是table 叫做user
這張表的欄位有三個

中文英文欄位型態
序號idint
姓名namevarchar2
年齡ageint
新增Table的欄位資料

下載 hibernate3 所需要的 jar , 下載

解壓縮後,請放到專案下的WebContent\WEB-INF\lib裡面去

首先在src下面建立個class對應資料庫的table
我的package 是 dao 裡面的 User.java
如下:

package dao;
public class User {
    private Integer id;
    private String name;
    private Integer age;
     
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }   
}

然後建立hibernate的xml
這裡是User.hbm.xml

class name就是剛剛的位置
table就是對應的表
剩下就是參數

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping 
 PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 
 
<hibernate-mapping> 
    <class name="dao.User" table="user"> 
        <id name="id" column="id"> 
            <generator class="native"/> 
        </id> 
        <property name="name" column="name"/> 
        <property name="age" column="age"/> 
    </class> 
</hibernate-mapping>

然後建立個介面放方法

package dao;
import java.util.*;
 
public interface IUserDAO {
    public void insert(User user);
    public User findById(Integer id);
    public List findAll();
    public void delete(Integer id);
}

然後實作

package dao;
import java.util.*;
import org.hibernate.Query;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
 
public class UserDAO implements IUserDAO{
    private SessionFactory sessionFactory;
     
    public UserDAO(){
    }
    public UserDAO(SessionFactory sessionFactory){
        this.setSessionFactory(sessionFactory);
    }
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
     
    public void insert(User user) {
        //get session
        Session session = sessionFactory.openSession();
        //Transaction
        Transaction tx =session.beginTransaction();
        //save
        session.save(user);
        tx.commit();
        session.close();
    }
     
    public User findById(Integer id) {
        //get session
        Session session = sessionFactory.openSession();
        //find
        User user = (User) session.get(User.class, id);
        Hibernate.initialize(user);
         
        //close
        session.close();
         
        return user;
    }
     
    public List findAll(){
        //get session
        Session session = sessionFactory.openSession();
        Query queryResult = session.createQuery("from User");
        return queryResult.list();
    }
 
    public void delete(Integer id) {
        //get session
        Session session = sessionFactory.openSession();
        Query queryResult = session.createQuery("from User where id = :id ");
        queryResult.setParameter("id", id);
        //Transaction
        Transaction tx =session.beginTransaction();
        User user = (User)queryResult.list().get(0);
        session.delete(user);
        tx.commit();
        session.close();
    }
     
}

因為hibernate會產生log
所以在WEB-INF建立個檔案log4j.properties

### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.SimpleLayout
log4j.rootLogger=WARN, stdout

然後要把跟他spring結合要修改web.xml和applicationContext.xml
web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>spring3</display-name>
   
  <!-- 多這個 -->
  <context-param>
        <param-name>log4jConfigLocation</param-name>  
        <param-value>/WEB-INF/log4j.properties</param-value>  
  </context-param>  
  <context-param>  
        <param-name>log4jRefreshInterval</param-name>  
        <param-value>60000</param-value>  
  </context-param>  
  <listener>  
        <listener-class>  
            org.springframework.web.util.Log4jConfigListener  
        </listener-class>  
  </listener>
  <!-- end -->
   
  <context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
   
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

applicationContext.xml
其中資料庫的ip
和使用者帳密 請填自己的XD

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="
 
http://www.springframework.org/schema/beans
 
 
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
 
 
http://www.springframework.org/schema/context
 
 
http://www.springframework.org/schema/context/spring-context-3.1.xsd
 
 
http://www.springframework.org/schema/tx
 
 
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
 
 
http://www.springframework.org/schema/aop
 
        http://www.springframework.org/schema/aop/spring-aop-3.1.xsd ">
 
    <!-- add here -->
     
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="org.gjt.mm.mysql.Driver" />
        <property name="url" value="jdbc:mysql://你的ip:3306/test?useUnicode=true&amp;characterEncoding=UTF-8" />
        <property name="username" value="XXX" />
        <property name="password" value="OOO" />
    </bean>
     
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="mappingResources">
            <list>
                <value>dao/User.hbm.xml</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">
                    org.hibernate.dialect.MySQLDialect
                </prop>
            </props>
        </property>
    </bean>
     
    <bean id="userDAO" class="dao.UserDAO">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
     
</beans>

這樣子hibernate就好了
測試的話

package dao;
 
import java.util.*;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
public class Demo {
 
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
         
        IUserDAO userDAO = (IUserDAO)context.getBean("userDAO");
         
        User user = new User();
        user.setName("ABC");
        user.setAge(30);
        userDAO.insert(user);
         
        List list = (List)userDAO.findAll();
         
        for(int i=0;i<list.size();i++){
            user = (User)list.get(i);
            System.out.println(user.getName());
        }
         
        userDAO.delete(1);
         
        for(int i=0;i<list.size();i++){
            user = (User)list.get(i);
            System.out.println(user.getName());
        }
    }
 
}

JOIN 怎麼設定

接下來是測試join table,先新增 table:GAY

中文英文欄位型態
序號idint
姓名name varchar2
電話tel varchar2
FKuser_idint
另一個有關聯的Table

在src下面再建立另一個class

我的package 是 dao2 裡面的 Gay.java
如下:

package dao2;
 
import dao.User;
 
public class Gay {
    private Integer id;
    private String name;
    private Integer tel;
    private User user;
     
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getTel() {
        return tel;
    }
    public void setTel(Integer tel) {
        this.tel = tel;
    }
    public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }
     
}

一樣建立Gay.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping 
 PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 
 
<hibernate-mapping>
    <class name="dao2.Gay" table="gay">
        <id name="id" column="id">
            <generator class="native"/>
        </id>
        <property name="name" column="name"/>
        <property name="tel" column="tel"/>
    <many-to-one name="user" class="dao.User" fetch="select">
            <column name="user_id" not-null="true" />
        </many-to-one>
    </class> 
</hibernate-mapping>

其中many-to-one就是跟user做關聯
一開始的name是class裡面的user 然後user_id是關聯的FK

還要修改之前的User.java

package dao;
 
import dao2.Gay;
import java.util.HashSet;
import java.util.Set;
 
public class User {
    private Integer id;
    private String name;
    private Integer age;
    private Set<Gay> gayset = new HashSet<Gay>(0);
     
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public Set<Gay> getGayset() {
        return gayset;
    }
    public void setGayset(Set<Gay> gayset) {
        this.gayset = gayset;
    }
     
}

User.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping 
 PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 
 
<hibernate-mapping> 
    <class name="dao.User" table="user"> 
        <id name="id" column="id"> 
            <generator class="native"/> 
        </id> 
        <property name="name" column="name"/> 
        <property name="age" column="age"/>
        <set name="gayset" table="gay" inverse="true" lazy="true" fetch="select">
            <key>
                <column name="user_id" not-null="true" />
            </key>
            <one-to-many class="dao2.Gay" />
        </set>
    </class> 
</hibernate-mapping>

user_id是關聯的FK

然後接下來就是測試了
IUserDAO.java 加了一個testjoin方法
然後在UserDAO實作

public void testjoin() {
        //get session
        Session session = sessionFactory.openSession();
         
        User user = new User();
        user.setName("GG");
        user.setAge(44);
        session.save(user);
         
        Gay gay = new Gay();
        gay.setName("GG");
        gay.setTel(0204);
         
        gay.setUser(user);
        user.getGayset().add(gay);
        session.save(gay);
         
        session.close();
    }

Demo.java

public static void main(String[] args) {
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    IUserDAO userDAO = (IUserDAO)context.getBean("userDAO");
 
userDAO.testjoin();
 
User user = new User();
Gay gay = new Gay();
 
List list = (List)userDAO.findAll();
         
        for(int i=0;i<list.size();i++){
            user = (User)list.get(i);
            System.out.println(user.getName());
        }
 
}