SPRING+JPA+Hibernate配置方法
1.applicationContext.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:p="http://www.springframework.org/schema/p"
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-4.1.xsd"> <!-- 扫描目录 -->
<context:component-scan base-package="com.genius"></context:component-scan>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<context:property-placeholder location="classpath:jdbc.properties" ignore-unresolvable="true"/> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="${jdbc.driver}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="user" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="initialPoolSize" value="${connection_pools.initial_pool_size}" />
<property name="minPoolSize" value="${connection_pools.min_pool_size}" />
<property name="maxPoolSize" value="${connection_pools.max_pool_size}" />
<property name="maxIdleTime" value="${connection_pools.max_idle_time}" />
<property name="acquireIncrement" value="${connection_pools.acquire_increment}" />
<property name="checkoutTimeout" value="${connection_pools.checkout_timeout}" />
</bean> <bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.genius.han.entity" />
<property name="persistenceProvider">
<bean class="org.hibernate.jpa.HibernatePersistenceProvider" />
</property>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="generateDdl" value="false" />
</bean>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop>
<prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop>
<prop key="hibernate.cache.region.factory_class">${hibernate.cache.region.factory_class}</prop>
<prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop>
<prop key="hibernate.jdbc.fetch_size">${hibernate.jdbc.fetch_size}</prop>
<prop key="hibernate.jdbc.batch_size">${hibernate.jdbc.batch_size}</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">false</prop>
<prop key="hibernate.use_sql_comments">false</prop>
<prop key="hibernate.connection.isolation">2</prop>
<prop key="javax.persistence.validation.mode">none</prop>
</props>
</property>
</bean> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean> <!-- 配置 Annotation 驱动,定义事务 -->
<tx:annotation-driven transaction-manager="transactionManager"
proxy-target-class="false" /> </beans>
jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/han?useUnicode=true&characterEncoding=UTF-8
jdbc.username=xxxx jdbc.password=xxxx #------------ ConnectionPools ------------
connection_pools.initial_pool_size=5
connection_pools.min_pool_size=5
connection_pools.max_pool_size=100
connection_pools.max_idle_time=600
connection_pools.acquire_increment=5
connection_pools.checkout_timeout=60000 hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.current_session_context_class=thread
hibernate.hbm2ddl.auto=update
hibernate.show_sql=true
hibernate.format_sql=false
hibernate.query.substitutions=Y hibernate.cache.use_second_level_cache=false
hibernate.cache.region.factory_class=org.hibernate.cache.impl.NoCachingRegionFactory
hibernate.cache.use_query_cache=false
hibernate.jdbc.fetch_size=50
hibernate.jdbc.batch_size=30
2. BaseDao
import java.io.Serializable; import javax.persistence.LockModeType;
import javax.persistence.Query; public interface BaseDao<T,ID extends Serializable> extends Serializable{ /**
* 查找实体对象
*
* @param id
* ID
* @return 实体对象,若不存在则返回null
*/
T find(ID id);
/**
* 查找实体对象
*
* @param id
* ID
* @param lockModeType
* 锁定方式
* @return 实体对象,若不存在则返回null
*/
T find(ID id, LockModeType lockModeType); /**
* 持久化实体对象
*
* @param entity
* 实体对象
*/
void persist(T entity); /**
* 合并实体对象
*
* @param entity
* 实体对象
* @return 实体对象
*/
T merge(T entity); /**
* 移除实体对象
*
* @param entity
* 实体对象
*/
void remove(T entity); /**
* 执行JPA原生sql查询
*
* @param sql
* */
public Query createNativeQuery(String sql); /**
* 刷新实体对象
*
* @param entity
* 实体对象
*/
void refresh(T entity); /**
* 刷新实体对象
*
* @param entity
* 实体对象
* @param lockModeType
* 锁定方式
*/
void refresh(T entity, LockModeType lockModeType); /**
* 获取实体对象ID
*
* @param entity
* 实体对象
* @return 实体对象ID
*/
ID getIdentifier(T entity); /**
* 判断是否为托管状态
*
* @param entity
* 实体对象
* @return 是否为托管状态
*/
boolean isManaged(T entity); /**
* 设置为游离状态
*
* @param entity
* 实体对象
*/
void detach(T entity); /**
* 锁定实体对象
*
* @param entity
* 实体对象
* @param lockModeType
* 锁定方式
*/
void lock(T entity, LockModeType lockModeType); /**
* 清除缓存
*/
void clear(); /**
* 同步数据
*/
void flush();
}
3. BaseDaoImpl
package com.genius.han.dao.impl; import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type; import javax.persistence.EntityManager;
import javax.persistence.LockModeType;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.Transactional; import org.springframework.util.Assert;
import org.springframework.util.StringUtils; import com.genius.han.dao.BaseDao; @Transactional
public class BaseDaoImpl<T, ID extends Serializable> implements BaseDao<T, ID> { private static final long serialVersionUID = 1L; private Class<T> entityClass; @PersistenceContext
protected EntityManager entityManager; @SuppressWarnings("unchecked")
public BaseDaoImpl()
{
Type type = getClass().getGenericSuperclass();
Type[] parameterizedType = ((ParameterizedType) type).getActualTypeArguments();
entityClass = (Class<T>) parameterizedType[0];
} @Override
public T find(ID id)
{
if (id != null)
{
return entityManager.find(entityClass, id);
}
return null;
} @Override
public T find(ID id, LockModeType lockModeType)
{
if (id != null)
{
if (lockModeType != null)
{
return entityManager.find(entityClass, id, lockModeType);
}
else
{
return entityManager.find(entityClass, id);
}
}
return null;
} @Override
public void persist(T entity)
{
Assert.notNull(entity);
entityManager.persist(entity); } @Override
public T merge(T entity)
{
Assert.notNull(entity);
return entityManager.merge(entity);
} @Override
public void remove(T entity)
{
Assert.notNull(entity);
if (entity != null)
{
entityManager.remove(entity);
}
} @Override
public Query createNativeQuery(String sql)
{
if (!StringUtils.isEmpty(sql))
{
return entityManager.createNativeQuery(sql);
}
return null;
} @Override
public void refresh(T entity)
{
Assert.notNull(entity);
if (entity != null)
{
entityManager.refresh(entity);
}
} @Override
public void refresh(T entity, LockModeType lockModeType)
{
Assert.notNull(entity);
if (entity != null)
{
if (lockModeType != null)
{
entityManager.refresh(entity, lockModeType);
}
else
{
entityManager.refresh(entity);
}
} } @SuppressWarnings("unchecked")
@Override
public ID getIdentifier(T entity)
{
Assert.notNull(entity);
if (entity != null)
{
return (ID) entityManager.getEntityManagerFactory().getPersistenceUnitUtil()
.getIdentifier(entity);
}
return null;
} @Override
public boolean isManaged(T entity)
{
Assert.notNull(entity);
if (entity != null)
{
return entityManager.contains(entity);
}
return false;
} @Override
public void detach(T entity)
{
Assert.notNull(entity);
if (entity != null)
{
entityManager.detach(entity);
}
} @Override
public void lock(T entity, LockModeType lockModeType)
{
Assert.notNull(entity);
Assert.notNull(lockModeType);
if (entity != null && lockModeType != null)
{
entityManager.lock(entity, lockModeType);
}
} @Override
public void clear()
{
entityManager.clear();
} @Override
public void flush()
{
entityManager.flush();
} }
4 Common Dao
import org.springframework.stereotype.Repository; @Repository
public class EmployeeDAO extends BaseDaoImpl<EmployeeEntity, Long> {
public void save(EmployeeEntity entity){
persist(entity);
}
}
5 BaseEntity
package com.genius.han.entity; import java.io.Serializable;
import java.util.Date; import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.Temporal;
import javax.persistence.TemporalType; import org.hibernate.search.annotations.DateBridge;
import org.hibernate.search.annotations.DocumentId;
import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.Index;
import org.hibernate.search.annotations.Resolution;
import org.hibernate.search.annotations.Store; @MappedSuperclass
public abstract class BaseEntity implements Serializable { private static final long serialVersionUID = -67188388306700736L; /** ID */
private Long id; /** 创建日期 */
private Date createDate = new Date(); /** 修改日期 */
private Date modifyDate = new Date(); /**
* 获取ID
*
* @return ID
*/ @DocumentId
@Id
// MySQL/SQLServer: @GeneratedValue(strategy = GenerationType.AUTO)
// Oracle: @GeneratedValue(strategy = GenerationType.AUTO, generator = "sequenceGenerator")
@GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() {
return id;
} public void setId(Long id) {
this.id = id;
} @Field(store = Store.YES, index = Index.UN_TOKENIZED)
@DateBridge(resolution = Resolution.SECOND)
@Column(name="CREATE_DATE",nullable = false, updatable = false)
@Temporal(TemporalType.TIMESTAMP)
public Date getCreateDate() {
return createDate;
} public void setCreateDate(Date createDate) {
this.createDate = createDate;
} @Field(store = Store.YES, index = Index.UN_TOKENIZED)
@DateBridge(resolution = Resolution.SECOND)
@Column(name="MODIFY_DATE",nullable = false)
@Temporal(TemporalType.TIMESTAMP)
public Date getModifyDate() {
return modifyDate;
} public void setModifyDate(Date modifyDate) {
this.modifyDate = modifyDate;
} /**
* 重写equals方法
*
* @param obj
* 对象
* @return 是否相等
*/
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (this == obj) {
return true;
}
if (!BaseEntity.class.isAssignableFrom(obj.getClass())) {
return false;
}
BaseEntity other = (BaseEntity) obj;
return getId() != null ? getId().equals(other.getId()) : false;
} /**
* 重写hashCode方法
*
* @return hashCode
*/
@Override
public int hashCode() {
int hashCode = 17;
hashCode += null == getId() ? 0 : getId().hashCode() * 31;
return hashCode;
} }
6.Common Entity
package com.genius.han.entity; import javax.persistence.Entity;
import javax.persistence.Table; @Entity
@Table(name="customerInfo")
public class CustomerInfoEntity extends BaseEntity{ /**
*
*/
private static final long serialVersionUID = -7920396843754746995L;
private String name;
private String gender;
private String email;
private String mobile_num; public CustomerInfoEntity(String name, String gender, String email,
String mobile_num) {
super();
this.name = name;
this.gender = gender;
this.email = email;
this.mobile_num = mobile_num;
} public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMobile_num() {
return mobile_num;
}
public void setMobile_num(String mobile_num) {
this.mobile_num = mobile_num;
}
}
SPRING+JPA+Hibernate配置方法的更多相关文章
- 【JPA】两种不同的实现jpa的配置方法
两种不同的实现jpa的配置方法 第一种: com.mchange.v2.c3p0.ComboPooledDataSource datasource.connection.driver_class=co ...
- 【spring boot hibernate】hibernate命名策略spring.jpa.hibernate.naming-strategy不起作用
对于 spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy hibernate命名策略设置之后 ...
- Spring JPA 简单配置使用
JPA 常用配置: # JPA (JpaBaseConfiguration, HibernateJpaAutoConfiguration) spring.data.jpa.repositories.b ...
- Spring JPA 定义查询方法
Spring JPA 定义查询方法 翻译:Defining Query Methods 存储库代理有两种方式基于方法名派生特定域的查询方式: 直接从方法名派生查询 自定义查询方式 可用选项基于 ...
- springmvc+spring+jpa(hibernate)+redis+maven配置
废话不多少 项目结构 pom.xml配置例如以下 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi=& ...
- Spring整合Hibernate的方法
一.基本支持 Spring 支持大多数流行的 ORM 框架, 包括 Hibernate JDO, TopLink, Ibatis 和 JPA. Spring 对这些 ORM 框架的支持是一致的, 因此 ...
- spring的事务配置方法
spring事务的配置有两种方式 1.xml配置的声明式事务配置 (1)配置数据源信息dataSource(使用阿里的数据源) <bean id="dataSource" c ...
- spring + springMVC +hibernate 配置2
这种方式比较精简 配置项不多 spring采用自动扫描配置 ,分spring_springMVC.xml . hibernate_config.xml 两个文件 web.xml配置如下 <?x ...
- Spring+Hibernate整合配置 --- 比较完整的spring、hibernate 配置
Spring+Hibernate整合配置 分类: J2EE2010-11-25 17:21 16667人阅读 评论(1) 收藏 举报 springhibernateclassactionservlet ...
随机推荐
- delphi基础篇之数据类型之三:3.结构类型(Struct)
3.结构类型(Struct) 结构类型在内存中存储一组相关的数据项,而不是像简单数据类型那样单一的数值.结构数据类型包括:集合类型.数组类型.记录类型.文件类型.类类型.类引用类型和接口类型等.
- MDK中问题:warning : type qualifier is meaningless on cast type return 的解决
在MDK编译代码时,有时会出现这样的警告, warning : type qualifier is meaningless on cast type return 在MDK中,作如下设置: 即添加 : ...
- 剑指offer第二版面试题9:用两个队列实现栈(JAVA版)
题目:用两个队列实现栈. 分析:通过一系列的栈的压入和弹出操作来分析用队列模拟一个栈的过程,如图所示,我们先往栈内压入一个元素a.由于两个队列现在都是空,我们可以选择把a插入两个队列中的任一个.我们不 ...
- PAT_A1028#List Sorting
Source: PAT A1028 List Sorting (25 分) Description: Excel can sort records according to any column. N ...
- 转载:vue-cli 脚手架 安装
声明:本文转载自https://www.cnblogs.com/loveyaxin/p/7094089.html 一. node安装 1)如果不确定自己是否安装了node,可以在命令行工具内执行: n ...
- 深入浅出JS:Two
JS中的Promise: MDN上面对promise的描述:Promise 对象用于表示一个异步操作的最终状态(完成或失败),以及其返回的值. 可以直接对字面上理解:Promise:承诺,一诺千金,只 ...
- 49-Ubuntu-其他命令-1-文件软链接
序号 命令 作用 01 ln -s 被链接的原文件 链接文件 建立文件的软链接,用通俗的方式讲类似于Windows下的快捷方式 注意: 没有-s选项建立的是一个硬链接文件--->>两个文件 ...
- Aria2 Centos8 安装配置
使用chkconfig 或者 chkconfig –list就可以看出当前系统已经设置的各个服务在各个运行级别下的开闭状态.如果我们想设置某个服务自启动或者关闭的话,那么只需要按照下面的格式使用即可 ...
- 使用net模块创建tcp服务器
demo /** * Created by ZXW on 2018/4/6. */ var net=require('net'); ; const HOST='localhost'; var clie ...
- CentOS7-安装最新版本GIT(git version 2.18.0)
Git安装方式有两种一种是yum安装一种是编译安装: 一.yum命令安装,此方法简单,会自动安装依赖的包,而且会从源里安装最新的版本,如果仓库不是最新的话安装的也不是最新Git. sudo yum i ...