Spring+Hibernate+MySql实例(注解)

Spring+Hibernate+MySql实例(注解)

在上一篇教程中,我们创建一个简单的Java项目结构,并演示如何使用Hibernate在Spring框架来在 MySQL数据库进行数据处理工作(插入,选择,更新和删除)。在本教程中,将学习如何使用Spring做同样的事情,只不过这一次我们使用 Hibernate 的注解方式。


最终项目结构

最终的项目文件结构看起来应该就像下面的图所示:

1.创建表

在MySQL数据库中创建一张“stock”表。 SQL语句如下:
CREATE TABLE  `zyiz`.`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=11 DEFAULT CHARSET=utf8;

2. Model & BO & DAO

模型中,业务对象(BO)和数据访问对象(DAO)模式是有助于清楚地识别层,以避免弄乱项目结构。
Stock Model (Annotation)
Stock模型注解类来存储库存数据。
package com.zyiz.stock.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

@Entity
@Table(name = "stock", catalog = "zyiz", uniqueConstraints = {
		@UniqueConstraint(columnNames = "STOCK_NAME"),
		@UniqueConstraint(columnNames = "STOCK_CODE") })
public class Stock implements java.io.Serializable {

	private Integer stockId;
	private String stockCode;
	private String stockName;

	public Stock() {
	}

	public Stock(String stockCode, String stockName) {
		this.stockCode = stockCode;
		this.stockName = stockName;
	}

	@Id
	@GeneratedValue(strategy = IDENTITY)
	@Column(name = "STOCK_ID", unique = true, nullable = false)
	public Integer getStockId() {
		return this.stockId;
	}

	public void setStockId(Integer stockId) {
		this.stockId = stockId;
	}

	@Column(name = "STOCK_CODE", unique = true, nullable = false, length = 10)
	public String getStockCode() {
		return this.stockCode;
	}

	public void setStockCode(String stockCode) {
		this.stockCode = stockCode;
	}

	@Column(name = "STOCK_NAME", unique = true, nullable = false, length = 20)
	public String getStockName() {
		return this.stockName;
	}

	public void setStockName(String stockName) {
		this.stockName = stockName;
	}

	@Override
	public String toString() {
		return "Stock [stockCode=" + stockCode + ", stockId=" + stockId
				+ ", stockName=" + stockName + "]";
	}
}
Stock Business Object (BO))
Stock 业务对象(BO)接口和实现,它是用来存储项目的业务功能,真正的数据库操作(CRUD)的工作不参与这一个类,而是用一个DAO(StockDao)类来做到这一点。
package com.zyiz.stock.bo;

import com.zyiz.stock.model.Stock;

public interface StockBo {
	
	void save(Stock stock);
	void update(Stock stock);
	void delete(Stock stock);
	Stock findByStockCode(String stockCode);
}
使这个类中的 Spring IoC容器的 bean“stockBo”自动装配库存DAO类。
package com.zyiz.stock.bo.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Service("stockBo")
public class StockBoImpl implements StockBo{
	
	@Autowired
	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类是直接扩展“HibernateDaoSupport“。但注释方式不可能做到这一点,因为没有办法从DAO类会话到工厂bean自动装配。解决方法是创建一个自定义类(CustomHibernateDaoSupport),并扩展了“HibernateDaoSupport”和自动装配会话工厂,DAO类扩展了这个类。

package com.zyiz.stock.dao;

import com.zyiz.stock.model.Stock;

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

}
package com.zyiz.util;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public abstract class CustomHibernateDaoSupport extends HibernateDaoSupport
{    
    @Autowired
    public void anyMethodName(SessionFactory sessionFactory)
    {
        setSessionFactory(sessionFactory);
    }
}
package com.zyiz.stock.dao.impl;

import java.util.List;

import org.springframework.stereotype.Repository;

import com.zyiz.stock.dao.StockDao;
import com.zyiz.stock.model.Stock;
import com.zyiz.util.CustomHibernateDaoSupport;

@Repository("stockDao")
public class StockDaoImpl extends CustomHibernateDaoSupport 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.资源配置

建立一个目录resources在“project_name/main/java/',它将用于存储Spring,Hibernate等配置文件。
Spring Configuration

数据库关联….

创建一个属性文件(database.properties)来存放数据库的详细信息,把它放到“resources/properties”文件夹中。 一个很好的做法是将数据库信息和Spring bean配置在不同的文件。

database.properties

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/zyiz
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 related….

创建一个会话工厂bean的配置文件(Hibernate.xml),把它放到“resources/database”文件夹中。在注释必须使用AnnotationSessionFactoryBean 来代替 LocalSessionFactoryBean,并注明您的注解模型类在“annotatedClasses”属性,而不是'mappingResources'属性。

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.annotation.AnnotationSessionFactoryBean">

    <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="annotatedClasses">
	<list>
		<value>com.zyiz.stock.model.Stock</value>
	</list>
    </property>

    </bean>
</beans>
导入所有的 Spring bean 配置文件合并为一个文件(BeanLocations.xml),把它放到“resources/config”文件夹。

BeanLocations.xml

导入Spring数据库配置并使用 Spring自动扫描功能。
<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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">

	<!-- Database Configuration -->
	<import resource="../database/DataSource.xml"/>
	<import resource="../database/Hibernate.xml"/>
	
	<!-- Auto scan the components -->
	<context:component-scan 
		base-package="com.zyiz.stock" />
	
</beans>

6. 运行它

把所有的文件和配置整合,运行它。
package com.zyiz.netmon;

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

import com.zyiz.stock.bo.StockBo;
import com.zyiz.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 zyiz.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 zyiz.stock stock0_ where stock0_.STOCK_CODE=?
Stock [stockCode=7667, stockId=3, stockName=HAIO]
Hibernate: update zyiz.stock set STOCK_CODE=?, STOCK_NAME=? where STOCK_ID=?
Hibernate: delete from zyiz.stock where STOCK_ID=?
Done


总结

所有的Spring,Hibernate相关类和配置文件都进行注解,它只是保留在XML文件中的数据库的详细信息。就个人而言,我不使用太多的注释功能,因为在某种程度上可能需要一些解决方法,像上面的“CustomHibernateDaoSupport'扩展'HibernateDaoSupport”。 在Spring和Hibernate的XML文件的成熟是一个更优的选择。

代码下载  - http://pan.baidu.com/s/1bewLiu

目录

Spring与其它Web框架集成