Spring+Hibernate+MySql範例


這個例子將建立一個簡單的 Java 專案結構,並演示如何使用 Hibernate 在Spring框架進行 MySQL 資料庫的資料處理工作(插入,選擇,更新和刪除)。


最終專案結構

最終的專案檔案結構應該看起來如下面的圖中顯示。

1.建立表

在MySQL資料庫中建立一張 「stock」表。 SQL語句如下:
CREATE TABLE  `yiibai`.`stock` (
  `STOCK_ID` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `STOCK_CODE` varchar(10) NOT NULL,
  `STOCK_NAME` varchar(20) NOT NULL,
  PRIMARY KEY (`STOCK_ID`) USING BTREE,
  UNIQUE KEY `UNI_STOCK_NAME` (`STOCK_NAME`),
  UNIQUE KEY `UNI_STOCK_ID` (`STOCK_CODE`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

2. Model & BO & DAO

模型中,業務物件(BO)和資料存取物件(DAO)模式是有助於清楚地識別層,以避免弄亂專案結構。
Stock Model
Stock 模型類以後用於儲存庫存資料。
package com.yiibai.stock.model;

import java.io.Serializable;

public class Stock implements Serializable {

	private static final long serialVersionUID = 1L;

	private Long stockId;
	private String stockCode;
	private String stockName;

	//getter and setter methods...
}
Stock Business Object (BO))
Stock 業務物件(BO)介面和實現,它是用來儲存專案的業務功能,真正的資料庫操作(CRUD)的工作不應該參與這一個類,而是有一個DAO(StockDao)類來做到這一點。
package com.yiibai.stock.bo;

import com.yiibai.stock.model.Stock;

public interface StockBo {
	
	void save(Stock stock);
	void update(Stock stock);
	void delete(Stock stock);
	Stock findByStockCode(String stockCode);
}
package com.yiibai.stock.bo.impl;

import com.yiibai.stock.bo.StockBo;
import com.yiibai.stock.dao.StockDao;
import com.yiibai.stock.model.Stock;

public class StockBoImpl implements StockBo{
	
	StockDao stockDao;
	
	public void setStockDao(StockDao stockDao) {
		this.stockDao = stockDao;
	}

	public void save(Stock stock){
		stockDao.save(stock);
	}
	
	public void update(Stock stock){
		stockDao.update(stock);
	}
	
	public void delete(Stock stock){
		stockDao.delete(stock);
	}
	
	public Stock findByStockCode(String stockCode){
		return stockDao.findByStockCode(stockCode);
	}
}
Stock Data Access Object

Stock DAO介面和實現,DAO實現類擴充套件了 Spring 的「HibernateDaoSupport」,以使Spring框架支援Hibernate。 現在,你可以通過getHibernateTemplate()執行 Hibernate 功能。

package com.yiibai.stock.dao;

import com.yiibai.stock.model.Stock;

public interface StockDao {
	
	void save(Stock stock);
	void update(Stock stock);
	void delete(Stock stock);
	Stock findByStockCode(String stockCode);

}
package com.yiibai.stock.dao.impl;

import java.util.List;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.yiibai.stock.dao.StockDao;
import com.yiibai.stock.model.Stock;

public class StockDaoImpl extends HibernateDaoSupport implements StockDao{
	
	public void save(Stock stock){
		getHibernateTemplate().save(stock);
	}
	
	public void update(Stock stock){
		getHibernateTemplate().update(stock);
	}
	
	public void delete(Stock stock){
		getHibernateTemplate().delete(stock);
	}
	
	public Stock findByStockCode(String stockCode){
		List list = getHibernateTemplate().find(
                      "from Stock where stockCode=?",stockCode
                );
		return (Stock)list.get(0);
	}

}

5.資源組態

用於儲存 Spring,Hibernate 等組態檔案。
Hibernate Configuration
建立 Hibernate 對映檔案(Stock.hbm.xml)的 Stock 表,把它放在「resources/hibernate/」檔案夾中。
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="com.yiibai.stock.model.Stock" table="stock" catalog="yiibai">
        <id name="stockId" type="java.lang.Long">
            <column name="STOCK_ID" />
            <generator class="identity" />
        </id>
        <property name="stockCode" type="string">
            <column name="STOCK_CODE" length="10" not-null="true" unique="true" />
        </property>
        <property name="stockName" type="string">
            <column name="STOCK_NAME" length="20" not-null="true" unique="true" />
        </property>
    </class>
</hibernate-mapping>
Spring Configuration

Database related….

建立一個屬性檔案(database.properties)資料庫的詳細資訊,把它放在「resources/properties」 檔案夾中。這是很好的做法,不同於資料庫細節並將 Spring bean 組態成不同的檔案。

database.properties

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/yiibai
jdbc.username=root
jdbc.password=password
為你的資料庫建立一個「dataSource」 bean組態檔案(DataSource.xml),並從database.properties匯入的屬性,把它放入到 「resources/database」 檔案夾中。

DataSource.xml

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
	
<bean 
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
	<property name="location">
		<value>properties/database.properties</value>
	</property>
</bean>

<bean id="dataSource" 
         class="org.springframework.jdbc.datasource.DriverManagerDataSource">
	<property name="driverClassName" value="${jdbc.driverClassName}" />
	<property name="url" value="${jdbc.url}" />
	<property name="username" value="${jdbc.username}" />
	<property name="password" value="${jdbc.password}" />
</bean>

</beans>

Hibernate 關聯….

建立一個對談工廠 bean 組態檔案(Hibernate.xml),把它放入 「resources/database」 檔案夾中。這個 LocalSessionFactoryBean 中設定一個共用的 Hibernate SessionFactory 在一個 Spring 應用程式上下文。

Hibernate.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
    
<!-- Hibernate session factory -->
<bean id="sessionFactory" 
     class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">

    <property name="dataSource">
      <ref bean="dataSource"/>
    </property>

    <property name="hibernateProperties">
       <props>
         <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
         <prop key="hibernate.show_sql">true</prop>
       </props>
     </property>
    	
     <property name="mappingResources">
	<list>
           <value>/hibernate/Stock.hbm.xml</value>
	</list>
      </property>	

    </bean>
</beans>

Spring beans related….

建立一個bean組態檔案(Stock.xml)的BO和DAO類,把它放入 「resources/spring」 檔案夾中。依賴的 DAO(stockDao)bean 注入到 bo(stockBo)bean; SessionFactory 的 bean 成stockDao。

Stock.xml

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

    <!-- Stock business object -->
   <bean id="stockBo" class="com.yiibai.stock.bo.impl.StockBoImpl" >
   		<property name="stockDao" ref="stockDao" />
   </bean>
 
   <!-- Stock Data Access Object -->
   <bean id="stockDao" class="com.yiibai.stock.dao.impl.StockDaoImpl" >
   		<property name="sessionFactory" ref="sessionFactory"></property>
   </bean>
   
</beans>
匯入所有的Spring bean組態檔案合併為一個檔案(BeanLocations.xml),把它變成了「resources/config」檔案夾。

BeanLocations.xml

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

	<!-- Database Configuration -->
	<import resource="../database/DataSource.xml"/>
	<import resource="../database/Hibernate.xml"/>
	
	<!-- Beans Declaration -->
	<import resource="../beans/Stock.xml"/>
	
</beans>

6. 執行它

把所有的檔案和組態,執行它。
package com.tw511.common;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.yiibai.stock.bo.StockBo;
import com.yiibai.stock.model.Stock;

public class App 
{
    public static void main( String[] args )
    {
    	ApplicationContext appContext = 
    	  new ClassPathXmlApplicationContext("spring/config/BeanLocations.xml");
	
    	StockBo stockBo = (StockBo)appContext.getBean("stockBo");
    	
    	/** insert **/
    	Stock stock = new Stock();
    	stock.setStockCode("7668");
    	stock.setStockName("HAIO");
    	stockBo.save(stock);
    	
    	/** select **/
    	Stock stock2 = stockBo.findByStockCode("7668");
    	System.out.println(stock2);
    	
    	/** update **/
    	stock2.setStockName("HAIO-1");
    	stockBo.update(stock2);
    	
    	/** delete **/
    	stockBo.delete(stock2);
    	
    	System.out.println("Done");
    }
}

輸出結果:


Hibernate: insert into yiibai.stock (STOCK_CODE, STOCK_NAME) values (?, ?)
Hibernate: select stock0_.STOCK_ID as STOCK1_0_, stock0_.STOCK_CODE as STOCK2_0_, stock0_.STOCK_NAME as STOCK3_0_ from yiibai.stock stock0_ where stock0_.STOCK_CODE=?
Stock [stockCode=7667, stockId=1, stockName=HAIO]
Hibernate: update yiibai.stock set STOCK_CODE=?, STOCK_NAME=? where STOCK_ID=?
Done


下載程式碼 – http://pan.baidu.com/s/1i4f40tB