最近在搭建Spring Boot项目的时候,因为项目较大的原因,由于直接继承spring boot自带的jpa会在Dao层写很多sql语句,且不能通用,于是抽象了一个底层方法,方便各层的继承。下面是抽象的底层类具体实现方法的部分代码。
BaseDaoImpl.java
@Transactional
public class BaseDaoImpl<T> implements IBaseDao<T> {
private Class<T> entityClass;
@Resource
private SessionFactory sessionFactory;
@SuppressWarnings("unchecked")
// 告诉编译器忽略指定的警告,不用在编译完成后出现警告信息
// 公共类
public BaseDaoImpl() {
ParameterizedType type = (ParameterizedType) getClass()
.getGenericSuperclass();
entityClass = (Class<T>) type.getActualTypeArguments()[0];
}
//Session
public Session getCurrentSession() {
Session session = null;
System.out.println("这是baseDao的session");
try {
session = sessionFactory.getCurrentSession();
} catch (Exception e) {
// TODO: handle exception
System.out.println(e);
}
return session;
}
@Override
public void save(T entity) {
// TODO Auto-generated method stub
System.out.println(entity);
getCurrentSession().save(entity);
}
@SuppressWarnings("unchecked")
@Override
public T get(Serializable id) {
// TODO Auto-generated method stub
System.out.println(entityClass);
return (T) getCurrentSession().get(entityClass, id);
}
一定要在该方法前面加
@Transactional
否则会报
否则会报
org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread
这是由于未开启Session Factroy事务注解。
下面我们来配置一下:
1.开启事物注解
@SpringBootApplication
@EnableTransactionManagement //开启事物注解
public class MindMapApplication {
public static void main(String[] args) {
SpringApplication.run(MindMapApplication.class, args);
}
}
2.配置一下SessionFactory
@Aspect
@Configuration
public class TxAdviceInterceptor {
// 超时时间 单位秒
private static final int TX_METHOD_TIMEOUT = 5;
private static final String AOP_POINTCUT_EXPRESSION = "execution (* com.hwj..service.*.*(..))";
@Autowired
private PlatformTransactionManager transactionManager;
@Bean
public TransactionInterceptor txAdvice() {
NameMatchTransactionAttributeSource source = new NameMatchTransactionAttributeSource();
// 只读事务,不做更新操作
RuleBasedTransactionAttribute readOnlyTx = new RuleBasedTransactionAttribute();
readOnlyTx.setReadOnly(true);
readOnlyTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_NOT_SUPPORTED );
// 当前存在事务就使用当前事务,当前不存在事务就创建一个新的事务
RuleBasedTransactionAttribute requiredTx = new RuleBasedTransactionAttribute();
requiredTx.setRollbackRules(
Collections.singletonList(new RollbackRuleAttribute(Exception.class)));
requiredTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
requiredTx.setTimeout(TX_METHOD_TIMEOUT);
Map<String, TransactionAttribute> txMap = new HashMap<>();
txMap.put("add*", requiredTx);
txMap.put("save*", requiredTx);
txMap.put("insert*", requiredTx);
txMap.put("update*", requiredTx);
txMap.put("delete*", requiredTx);
txMap.put("get*", readOnlyTx);
txMap.put("query*", readOnlyTx);
source.setNameMap( txMap );
TransactionInterceptor txAdvice = new TransactionInterceptor(transactionManager, source);
return txAdvice;
}
@Bean
public Advisor txAdviceAdvisor() {
AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
pointcut.setExpression(AOP_POINTCUT_EXPRESSION);
return new DefaultPointcutAdvisor(pointcut, txAdvice());
}
@Bean //一定要注入这个(划重点)
public SessionFactory sessionFactory(HibernateEntityManagerFactory hemf){
return hemf.getSessionFactory();
}
}
基本的配置已经好了,现在就可以在spring boot里用hibernate中的Session Factory了。
调用的时候
@Resource
private SessionFactory sessionFactory;
@Override
public Session getCurrentSession() {
Session session = null;
try {
session = this.sessionFactory.getCurrentSession();
}catch (Exception e) {
System.out.println(e);
}
System.out.println(session);
return session;
}