Spring 整合 Hibernate
這篇文章將展示如何使用 Hibernate 在 Spring框架進行 MySQL 資料庫的資料處理工作(插入,選擇,更新和刪除)。由IOC容器來管理Hibernate的SessionFactory,讓Hibernate使用上Spring的宣告式事務。
1. 建立表結構
CREATE TABLE `article` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(100) NOT NULL DEFAULT '',
`content` text,
PRIMARY KEY (`id`)
);
2. 建立專案spring-hibernate
3. pom.xml配置檔案新增jar依賴
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.angelia</groupId>
<artifactId>spring-hibernate</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-hibernate</name>
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>5.0.9.RELEASE</spring.version>
<hibernate.version>5.2.1.Final</hibernate.version>
</properties>
<dependencies>
<!-- spring需要的jar包依賴 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- hibernate的jar包依賴 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- mysql的jar包依賴 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.12</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- AspectJ依賴jar -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.9.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjtools -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjtools</artifactId>
<version>1.9.0</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.0</version>
</dependency>
</dependencies>
</project>
4. 建立實體類,資料訪問物件和業務物件
業務物件(Service)和資料訪問物件(DAO)模式是有助於清楚地識別層。
public class Article {
private int id;
private String title;
private String content;
// getters and setters
}
public interface ArticleDao {
public void insert(Article article);
public void update(Article article);
public void delete(Article article);
public List<Article> getArticles();
public Article getArticleById(int id);
}
public class ArticleDaoImpl extends HibernateDaoSupport implements ArticleDao {
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);
}
}
public interface ArticleService {
public void save(Article article);
public void update(Article article);
public void remove(Article article);
public List<Article> findArticles();
public Article findArticleById(int id);
}
public class ArticleServiceImpl implements ArticleService {
private ArticleDao articleDao;
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);
}
}
5. 資源配置
建立 Article 的 Hibernate 對映檔案 Article.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="com.angelia.sh.model.Article" table="article" >
<id name="id">
<column name="id" />
<generator class="increment"></generator>
</id>
<property name="title" type="string">
<column name="title" length="100" not-null="true" />
</property>
<property name="content" type="string">
<column name="content"/>
</property>
</class>
</hibernate-mapping>
建立Hibernate配置檔案Hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<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"/>
</session-factory>
</hibernate-configuration>
建立Spring的資料來源配置檔案 database.properties, Spring-Datasource.xml
jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring_hibernate?useSSL=false&serverTimezone=UTC
jdbc.username=root
jdbc.password=root
<?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: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" /> -->
<!-- 配置事務事務屬性 -->
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="remove*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="insert*" propagation="REQUIRED" />
<tx:method name="*" read-only="true" />
</tx:attributes>
</tx:advice>
<!-- 配置事務切點,並把切點和事務屬性關聯起來 -->
<aop:config>
<aop:pointcut expression="execution(public * com.angelia.sh.service.ArticleServiceImpl*.*(..))" id="txPointcut" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut" />
</aop:config>
</beans>
常見Beans配置檔案Spring-Bean.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">
<bean id="articleService" class="com.angelia.sh.service.ArticleServiceImpl">
<property name="articleDao" ref="articleDao" />
</bean>
<!-- Article Data Access Object -->
<bean id="articleDao" class="com.angelia.sh.dao.ArticleDaoImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
</beans>
匯入所有的Spring bean配置檔案合併為一個檔案(Spring-Hibernate-All-Cfg.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">
<!-- Database Configuration -->
<import resource="Spring-Datasource.xml" />
<!-- Beans Declaration -->
<import resource="Spring-Bean.xml" />
</beans>
6. 建立測試類,執行它。
public class SpringHibernateTest {
@Test
public void shouldAnswerWithTrue() {
ApplicationContext context = new ClassPathXmlApplicationContext("Spring-Hibernate-All-Cfg.xml");
ArticleService articleService = (ArticleService) context.getBean("articleService");
/** save **/
Article article = new Article();
article.setTitle("Spring 整合 Hibernate");
article.setContent("Spring 整合 Hibernate 詳解");
articleService.save(article);
/** select **/
Article article2 = articleService.findArticleById(1);
System.out.println(article2);
/** update **/
article2.setContent("Spring 整合 Hibernate 詳解 被更新了。。。");
articleService.update(article2);
/** remove **/
articleService.remove(article2);
System.out.println(articleService.findArticles());
}
}
程式碼連結: https://pan.baidu.com/s/1U2YEoGzovhB9UjdOvgMW_w 密碼: jdr4
相關文章
- sh_Spring整合HibernateSpring
- FLEX和spring、hibernate的整合FlexSpring
- [摘]Struts+Spring+Hibernate整合Spring
- Spring整合Hibernate的事務管理Spring
- 【SSH框架】系列之 Spring 整合 Hibernate 框架框架Spring
- Spring與Hibernate整合中的session問題SpringSession
- spring json dwr struts2.0 hibernate整合SpringJSON
- Hibernate--與Spring整合及增刪改查Spring
- struts+hibernate+spring 整合中出現的問題Spring
- Struts2+hibernate+spring配置程式整合下載Spring
- 框架(Spring、Struts2和Hibernate三者)整合框架Spring
- Spring4學習(四)Spring4中整合Hibernate4Spring
- SSH開發實踐part1:Spring與Hibernate整合Spring
- Hibernate,Weblogic整合問題Web
- Spring mvc+struts2+Hibernate整合例項程式碼(註解詳解)SpringMVC
- [java web]Idea+maven+spring4+hibernate5+struts2整合過程JavaWebIdeaMavenSpring
- JPA/Hibernate/Spring Data概念Spring
- Spring boot 四 JPA HibernateSpring Boot
- 使用Spring整合Hibernate,並實現對資料表的增、刪、改、查的功能Spring
- Spring Boot整合Spring BatchSpring BootBAT
- Spring Boot整合Spring SecuritySpring Boot
- Spring Boot整合Spring AopSpring Boot
- Spring 整合 MyBatisSpringMyBatis
- mybatis整合springMyBatisSpring
- ActiveMq整合SpringMQSpring
- Spring整合MyBatisSpringMyBatis
- Spring整合JUnitSpring
- Spring整合WebSocketSpringWeb
- Spring Cloud 整合SpringCloud
- 求助於struts+spring+hibernateSpring
- Spring與hibernate的問題Spring
- spring struts hibernate 優缺點?Spring
- MyBatis(九) 整合Spring、整合SpringMVCMyBatisSpringMVC
- 整合struts和hibernate開發嚮導 (轉)
- SSH三大框架的搭建整合(Spring+Hibernate+Struts2)實現增刪改查登入框架Spring
- struts2.3+hibernate4.1+spring3.2+EasyUI1.36整合實現的java後臺管理系統SpringUIJava
- Spring Boot:整合Spring Data JPASpring Boot
- spring:spring與mybatis的整合SpringMyBatis