您的位置:首页 > 其它

框架集成hibernate的增删改查

2016-04-28 11:53 232 查看
1.添加jar包
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.12</version>
</dependency>

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.9</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.32</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.5.Final</version>
</dependency>
2.数据源,事务配置文件
applicationContext-dataaccess.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"
xmlns:context="http://www.springframework.org/schema/context"
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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> 
<!-- 使用annotation 自动注册bean, 并保证@Required、@Autowired的属性被注入 -->
<context:component-scan base-package="com">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

<!-- 加载配置文件 -->
<context:property-placeholder location="classpath:jdbc.properties" />

<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close">
<!-- 基本属性 url、user、password -->
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<!-- 配置初始化大小、最小、最大 -->
<property name="initialSize" value="1" />
<property name="minIdle" value="1" />
<property name="maxActive" value="20" />

<!-- 配置获取连接等待超时的时间 -->
<property name="maxWait" value="60000" />

<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis"
value="60000" />

<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis"
value="300000" />

</bean>

<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan">
<list>
<value>com.*.*.*.entity</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>

<!-- 用于调试的属性 -->
<prop key="hibernate.show_sql">show</prop>
<prop key="hibernate.format_sql">show</prop>

<!--
create:表示启动的时候先drop,再create
create-drop: 也表示创建,只不过再系统关闭前执行一下drop
update: 这个操作启动的时候会去检查schema是否一致,如果不一致会做scheme更新
validate: 启动时验证现有schema与你配置的hibernate是否一致,如果不一致就抛出异常,并不做更新
-->
<prop key="hibernate.hbm2ddl.auto">validate</prop>

<!-- 用于解决懒加载时找不到session的问题 -->
<!-- 关闭Load方法的延迟加载 ?-->
<!-- <prop key="hibernate.enable_lazy_load_no_trans">true</prop> -->
</props>
</property>
</bean>

<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>

<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!-- hibernate4必须配置为开启事务 否则 getCurrentSession()获取不到 -->
<tx:method name="save*" propagation="REQUIRED" rollback-for="java.lang.Exception" />
<tx:method name="add*" propagation="REQUIRED"  rollback-for="java.lang.Exception"/>
<tx:method name="create*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
<tx:method name="insert*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
<tx:method name="update*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
<tx:method name="merge*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
<tx:method name="del*" propagation="REQUIRED"	rollback-for="java.lang.Exception"/>
<tx:method name="remove*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
<tx:method name="use*" propagation="REQUIRED" read-only="true"/>
<tx:method name="load*" propagation="REQUIRED" read-only="true"/>
<tx:method name="get*" propagation="REQUIRED" read-only="true"/>
<tx:method name="count*" propagation="REQUIRED" read-only="true" />
<tx:method name="find*" propagation="REQUIRED" read-only="true" />
<tx:method name="select*" propagation="REQUIRED" read-only="true" />
<tx:method name="list*" propagation="REQUIRED" read-only="true" />
<tx:method name="*" read-only="true" />
</tx:attributes>
</tx:advice>

<aop:config expose-proxy="true">
<!-- 只对业务逻辑层实施事务 -->
<aop:pointcut id="txPointcut" expression="execution(* com.*.*.*.service..*.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
</aop:config>

</beans>
3.jdbc.properties
jdbc.driverClassName=com.mysql.jdbc.Driver

jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8

jdbc.username=root

jdbc.password=1234

4.com.ln.baseframe.common.dao.IBaseDao

package com.ln.baseframe.common.dao;

import java.io.Serializable;

public interface IBaseDao {

public Serializable save(Object entity);

public <T> void delete(Class<T> clazz,Serializable id);

public void update(Object entity);

public <T> T getById(Class<T> clazz,Serializable id);

}
5.com.ln.baseframe.common.dao.impl.BaseDao

package com.ln.baseframe.common.dao.impl;

import java.io.Serializable;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.ln.baseframe.common.dao.IBaseDao;

@Repository("baseDao")
public class BaseDao implements IBaseDao {

@Autowired
private SessionFactory  sessionFactory;

public Session getSession() {
// 事务必须是开启的(Required),否则获取不到
return sessionFactory.getCurrentSession();
}

@Override
public Serializable save(Object entity) {
return this.getSession().save(entity);
}

@Override
public <T> void delete(Class<T> clazz, Serializable id) {
this.getSession().delete(this.getById(clazz, id));
}

@Override
public void update(Object entity) {
this.getSession().update(entity);
}

@Override
public <T> T getById(Class<T> clazz, Serializable id) {
return (T) this.getSession().get(clazz, id);
}

}
6.com.ln.baseframe.common.service.IBaseService
package com.ln.baseframe.common.service;

import java.io.Serializable;

public interface IBaseService {

public Serializable save(Object entity);

public <T> void delete(Class<T> clazz,Serializable id);

public void update(Object entity);

public <T> T getById(Class<T> clazz,Serializable id);
}
7.com.ln.baseframe.common.service.impl.BaseService
package com.ln.baseframe.common.service.impl;

import java.io.Serializable;

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

import com.ln.baseframe.common.dao.IBaseDao;
import com.ln.baseframe.common.service.IBaseService;

@Service
public class BaseService implements IBaseService{

@Autowired
protected IBaseDao baseDao;

@Override
public Serializable save(Object entity) {
return baseDao.save(entity);
}

@Override
public <T> void delete(Class<T> clazz, Serializable id) {
baseDao.delete(clazz, id);
}

@Override
public void update(Object entity) {
baseDao.update(entity);
}

@Override
public <T> T get
ae26
ById(Class<T> clazz, Serializable id) {
return baseDao.getById(clazz, id);
}

}
8.com.ln.baseframe.common.entity.IdEntity1

package com.ln.baseframe.common.entity;

import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;

@MappedSuperclass
public abstract class IdEntity1 {

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;

public long getId() {
return id;
}

public void setId(long id) {
this.id = id;
}

}
9.com.ln.baseframe.common.entity.Department1
package com.ln.baseframe.common.entity;

import javax.persistence.Entity;
import javax.persistence.Table;

@Entity
@Table(name="t_department1")
public class Department1 extends IdEntity1{

private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}
10.com.ln.baseframe.common.utils.SpringUtils
package com.ln.baseframe.common.utils;

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

public class SpringUtils {

public static ApplicationContext ac;

static{
ac=new ClassPathXmlApplicationContext("applicationContext-dataaccess.xml");
}

public static Object getBean(String servicename){
return ac.getBean(servicename);
}

}
11.TestBaseService
package common;

import com.ln.baseframe.common.entity.Department1;
import com.ln.baseframe.common.service.IBaseService;
import com.ln.baseframe.common.utils.SpringUtils;

import junit.framework.Assert;
import junit.framework.TestCase;

public class TestBaseService extends TestCase {

IBaseService baseService;

protected void setUp() throws Exception {
baseService=(IBaseService) SpringUtils.ac.getBean("baseService");
}

public void testAddDepartment() {
Department1 department1=new Department1();
department1.setName("研发部门");
baseService.save(department1);
/*Department2 department2=new Department2();
department2.setName("运营部门");
baseService.save(department2);*/
}

public void testUpdateDepartment(){
Department1 department1=baseService.getById(Department1.class, 2L);
department1.setName("运维部门");
baseService.update(department1);

department1=baseService.getById(Department1.class, 2L);
Assert.assertEquals("运维部门", department1.getName());
}

public void testDelDepartment(){
Department1 department1=baseService.getById(Department1.class, 2L);
baseService.delete(Department1.class, department1.getId());
department1=baseService.getById(Department1.class, 2L);
Assert.assertEquals(null, department1);
}

}
集成完毕!

如果要集成到web环境需要在web.xml配置文件加入如下配置:

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:applicationContext-*.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: