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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AngeliaZheng

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值