记录一下自己通过网上查找和摸索回来的spring4和hibernate4的整合,包管理工具用的是Maven,数据库用的是Mysql。
- 项目目录结构
- pom.xml文件
- 配置属性文件
- spring配置文件application.xml
- 自定义HibernateUtils工具类
- pom.xml文件
- 基本CRUD操作
创建Person实体类
创建PersonDao Dao层
创建PersonService Service层- 单元测试
文件目录结构
pom.xm 文件
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.jdk.version>1.8</project.jdk.version>
<spring.version>4.3.0.RELEASE</spring.version>
<hibernate.version>4.3.11.Final</hibernate.version>
<mysql.version>5.1.38</mysql.version>
<junit.version>4.12</junit.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<!-- spring依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</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-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- hibernate 依赖 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.13</version>
</dependency>
<!-- mysql 连接依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<!-- maven -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>${project.jdk.version}</source>
<target>${project.jdk.version}</target>
</configuration>
</plugin>
</plugins>
</build>
配置属性文件
jdbc.driverClassName = com.mysql.jdbc.Driver
jdbc.url = jdbc\:mysql\://localhost\:3306/db_test?useUnicode\=true&characterEncoding\=UTF-8
jdbc.username = root
jdbc.password = 123456
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.hbm2ddl.auto=update
hibernate.show_sql=true
hibernate.format_sql=true
spring配置文件application.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd">
<context:component-scan base-package="com.lwb" />
<context:property-placeholder location="classpath:config/config.properties" />
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="${jdbc.driverClassName}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="maxPoolSize" value="40"></property>
<property name="minPoolSize" value="1"></property>
<property name="initialPoolSize" value="1"></property>
<property name="maxIdleTime" value="20"></property>
</bean>
<!-- Hibernate session factory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.lwb.entity" />
<property name="hibernateProperties">
<props>
<!--hibernate根据实体自动生成数据库表 -->
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<!--指定数据库方言 -->
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<!--在控制台显示执行的数据库操作语句 -->
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<!--在控制台显示执行的数据哭操作语句(格式) -->
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
</props>
</property>
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 事务扫描开始(开启注解式声明,@Tranctional) -->
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- start spring集中式声明 -->
<!-- <tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
hibernate4必须配置为开启事务 否则 getCurrentSession()获取不到session
<tx:method name="*" propagation="REQUIRED" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="productServiceMethods" expression="execution(* com.lwb.service.*.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="productServiceMethods" />
</aop:config> -->
<!-- spring集中式声明 -->
<bean id="hibernateUtils" class="com.lwb.util.HibernateUtils" init-method="init">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
</beans>
自定义HibernateUtils工具类
public class HibernateUtils {
public static final ThreadLocal threadLocal= new ThreadLocal();
public static SessionFactory sessionFactory;
public void init(){
System.out.println("...... 初始化 ......" );
}
/**
* 获取当前的Session
* @return
*/
public static Session currentSession(){
Session session = (Session) threadLocal.get();
if(ObjectUtils.isEmpty(session)){
session = sessionFactory.getCurrentSession();
threadLocal.set(session);
}
return session;
}
/**
* 释放Session
*/
public static void closeSession(){
Session session = (Session) threadLocal.get();
if(ObjectUtils.isEmpty(session)){
session.close();
}
threadLocal.set(null);
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void setSessionFactory(SessionFactory sessionFactory) {
HibernateUtils.sessionFactory = sessionFactory;
}
public static ThreadLocal getThreadlocal() {
return threadLocal;
}
}
创建Person实体类
@Entity
@Table(name = "db_person")
public class Person {
@Id
@GeneratedValue
@Column(name = "PK_ID")
private int pkId;
@Column(name = "NAME")
private String name;
@Column(name = "AGE")
private int age;
@Column(name = "ADDRESS")
private String address;
public int getPkId() {
return pkId;
}
public void setPkId(int pkId) {
this.pkId = pkId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Person [pkId=" + pkId + ", name=" + name + ", age=" + age + ", address=" + address + "]";
}
}
创建PersonDao Dao层
@Repository
public class PersonDao extends BaseDao<Person> {
@Override
public void insert(Person entity) {
HibernateUtils.currentSession().save(entity);
}
@Override
public Person get(int pkId) {
return (Person) HibernateUtils.currentSession().get(Person.class, pkId);
}
@Override
public List<Person> getLists() {
String hql = "from Person";
Query query = HibernateUtils.currentSession().createQuery(hql);
return query.list();
}
@Override
public void Delete(int pkId) {
Person person = get(pkId);
HibernateUtils.currentSession().delete(person);
}
@Override
public void update(Person entity) {
HibernateUtils.currentSession().update(entity);
}
}
创建PersonService Service层
@Service
public class PersonService {
@Autowired
PersonDao personDao;
@Transactional
public void insert(Person person) {
personDao.insert(person);
}
@Transactional
public void delete(int pkId) throws Exception {
personDao.Delete(pkId);
}
@Transactional
public void update(Person person) {
personDao.update(person);
}
@Transactional
public void get(int pkId) {
System.out.println("======打印数据======" + personDao.get(pkId));
}
@Transactional
public void getLists() {
List<Person> list = personDao.getLists();
for (Person person : list) {
System.out.println("====== 打印数据 =====" + person);
}
}
}
单元测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring/application.xml"})
public class OneTest {
@Autowired
PersonService personService;
@Test
public void insert() {
Person person = new Person();
person.setName("王五");
person.setAge(23);
person.setAddress("中华人民共和国");
person.setPkId(26);
personService.insert(person);
}
@Test
public void delete() throws Exception {
personService.delete(25);
}
@Test
public void update() {
Person person = new Person();
person.setPkId(15);
personService.update(person);
}
@Test
public void get() {
personService.get(22);
}
@Test
public void getLists() {
personService.getLists();
}
}
此文章并非原创 ,部分摘抄自网上资源。