1. 程式人生 > >Spring 整合 Hibernate 註解方式

Spring 整合 Hibernate 註解方式

上一篇文章中,我們建立一個簡單的Maven專案結構,並展示如何使用 Spring 和 Hibernate 框架在 MySQL資料庫進行資料處理工作(插入,選擇,更新和刪除)。在本文章中,還是學習如何使用 Spring 和 Hibernate 做同樣的事情,這一次我們使用註解方式。

1. Article模型用註解來儲存庫存資料。

@Entity
@Table(name = "article")
public class Article {
	private int id;
	private String title;
	private String content;
	
	public Article() {
		super();
	}

	public Article(int id, String title, String content) {
		super();
		this.id = id;
		this.title = title;
		this.content = content;
	}
	
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "id", unique = true, nullable = false)
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	
	@Column(name = "title", nullable = false, length = 100)
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	
	@Column(name = "content", nullable = false, length = 100)
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}

	@Override
	public String toString() {
		return "Article [id=" + id + ", title=" + title + ", content="
				+ content + "]";
	}
}

2. Article資料訪問物件

Article DAO介面和實現。在上一篇文章中,DAO類是直接擴充套件“HibernateDaoSupport“。但註釋方式不可能做到這一點,因為沒有辦法從DAO類會話到工廠bean自動裝配。解決方法是建立一個方法自動裝配會話工廠。如下:

@Transactional
@Repository("articleDao")
public class ArticleDaoImpl extends HibernateDaoSupport implements ArticleDao {
	/**
	 * 由於使用的是spring的annotation注入,HibernateDaoSupport不能注入sessionFactiry和hibernateTemplemet。
	 */
	@Resource
	public void setMySessionFactory(SessionFactory sessionFactory){  
		super.setSessionFactory(sessionFactory);  
	}

	public void insert(Article article) {
		getHibernateTemplate().save(article);
	}

	public void update(Article article) {
		getHibernateTemplate().update(article);
	}

	public void delete(Article article) {
		getHibernateTemplate().delete(article);
	}

	public List<Article> getArticles() {
		//from 類名(Article),注意大小寫
		return (List<Article>) getHibernateTemplate().find("from Article");
	}

	public Article getArticleById(int id) {
		List articles = getHibernateTemplate().find("from Article where id = ?", id);
		return (Article) articles.get(0);
	}
}

3. Article業務物件

@Service("articleService")
public class ArticleServiceImpl implements ArticleService {
	
	private ArticleDao articleDao;
	@Autowired
	public void setArticleDao(ArticleDao articleDao) {
		this.articleDao = articleDao;
	}
	public void save(Article article) {
		articleDao.insert(article);
	}
	public void update(Article article) {
		articleDao.update(article);
	}
	public void remove(Article article) {
		articleDao.delete(article);
	}
	public List<Article> findArticles() {
		return articleDao.getArticles();
	}
	public Article findArticleById(int id) {
		return articleDao.getArticleById(id);
	}
}

4. 資源配置,修改Hibernate.cfg.xml,Spring-Bean.xml和Spring-Datasource.xml如下:

<hibernate-configuration>
    <session-factory>
        <!-- 配置Hibernate的基本屬性 -->
        <!-- 1.資料來源配置到IOC容器中 -->
        <!-- 2.關聯的.hbm.xml也在IOC容器配置SessionFactory例項 -->
        <!-- 3.配置Hibernate的基本屬性:方言,SQL顯示及格式化,生成資料表的策略以及二級快取 -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
        <property name="hibernate.show_sql">true</property>
        <property name="hbm2ddl.auto">update</property>
        
        <!-- <mapping resource="Article.hbm.xml"/> -->
        <mapping class="com.angelia.sh.model.Article"/>
    </session-factory>
</hibernate-configuration>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:aop="http://www.springframework.org/schema/aop" 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
	http://www.springframework.org/schema/aop 
	http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

	<!-- Auto scan the components -->
	<context:component-scan base-package="com.angelia.sh" />
</beans>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">

	<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="location">
			<value>database.properties</value>
		</property>
	</bean>

	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<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>

	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
		<!-- 注入datasource,給sessionfactoryBean內setdatasource提供資料來源 -->
		<property name="dataSource" ref="dataSource" />
		<!-- 載入hibernate配置檔案 -->
		<property name="configLocation" value="Hibernate.cfg.xml"></property>
	</bean>

	<!-- 配置Spring宣告式事務 -->
	<bean id="txManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>
	<tx:annotation-driven transaction-manager="txManager" />
</beans>

5. 執行測試類,結果和上一篇文章一樣

程式碼下載連結: https://pan.baidu.com/s/1RhusIDwlUVW-r9NvF-9Mnw 密碼: k3yn