首页 > 代码库 > springboot 获取hibernate 的 SessionFactory

springboot 获取hibernate 的 SessionFactory

注入bean

package cn.xiaojf;

import cn.xiaojf.today.data.rdb.repository.RdbCommonRepositoryImpl;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.vendor.HibernateJpaSessionFactoryBean;

@SpringBootApplication
@EnableJpaRepositories(repositoryBaseClass = RdbCommonRepositoryImpl.class)
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Bean
    public HibernateJpaSessionFactoryBean sessionFactory() {
        return new HibernateJpaSessionFactoryBean();
    }
}

application.properties 中配置

spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto=none
spring.jpa.database=mysql
spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext

直接在代码中注入

@Autowired
private SessionFactory sessionFactory;

例子

package cn.xiaojf.today.base.service.impl;

import cn.xiaojf.today.base.constant.SystemConstant;
import cn.xiaojf.today.base.service.EntityService;
import cn.xiaojf.today.base.util.Asserts;
import cn.xiaojf.today.base.util.BeanUtil;
import cn.xiaojf.today.base.util.DaoUtil;
import cn.xiaojf.today.base.util.StringUtil;
import cn.xiaojf.today.data.rdb.entity.AbstractEntity;
import cn.xiaojf.today.data.rdb.entity.BaseEntity;
import cn.xiaojf.today.data.rdb.util.EntityUtil;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Example;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

/**
* @author xiaojf 2017/2/24 11:06.
*/
@Service
@Transactional
public class EntityServiceImpl implements EntityService {
@Autowired
private SessionFactory sessionFactory;


@Override
public <T extends BaseEntity> boolean checkFieldRepeat(T entity, String fieldName) throws Exception{
String id = StringUtil.toString(BeanUtils.getProperty(entity, "id"));
Serializable filedValue = http://www.mamicode.com/StringUtil.toString(BeanUtils.getProperty(entity, fieldName));

BaseEntity baseEntity = entity.getClass().newInstance();
BeanUtils.setProperty(baseEntity, fieldName, filedValue);
List list = this.findByExample(baseEntity);

if (list != null && list.size() > 0) {
Object o = list.get(0);
String existId = BeanUtils.getProperty(o, "id");
if (existId.equals(id)) {
return false;
} else {
return true;
}
}
return false;
}

@Override
public <T extends BaseEntity> void saveOrUpdate(T entity) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
String id = BeanUtils.getProperty(entity, SystemConstant.TABLE_ID);
Session session = this.getSession();
if(! StringUtils.isBlank(id)) {//更新操作
T origion = this.get(entity.getClass(),id);
BeanUtil.copyPropertiesIgnoreNull(entity, origion);
DaoUtil.generateDefaultField(origion); //追加部分字段默认值
session.update(origion);
} else { //新增
DaoUtil.generateDefaultField(entity); //追加部分字段默认值
session.save(entity);
}
}

@Override
public <T extends BaseEntity> void saveOrUpdate(List<T> list) throws Exception {
Asserts.notNull(list);
for (T t : list) {
getSession().saveOrUpdate(t);
}
}

@Override
public void enable(Class clazz, List<String> ids) throws Exception {
List<BaseEntity> list = get(clazz, ids);
for (BaseEntity t : list) {
BeanUtils.setProperty(t, "status", AbstractEntity.STATUS_ENABLED);
}

saveOrUpdate(list);
}

@Override
public void disable(Class clazz, List<String> ids) throws Exception {
List<BaseEntity> list = get(clazz, ids);
for (BaseEntity t : list) {
BeanUtils.setProperty(t, SystemConstant.TABLE_STATUS, AbstractEntity.STATUS_DISABLED);
}

saveOrUpdate(list);
}

@Override
public <T extends BaseEntity> T get(Class clazz ,Serializable id) {
if (id == null) {
return null;
}

return (T) this.getSession().get(clazz, id);
}

@Override
public <T extends BaseEntity> List<T> get(Class clazz, List<String> ids) {
Asserts.notNull(ids, "主键不能为空");
List<T> list = new ArrayList<T>();
for (String id : ids) {
T t = get(clazz, id);
list.add(t);
}
return list;
}


@Override
public void logDelById(Class clazz, String id) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
Asserts.notNull(id);
Asserts.notNull(clazz);
BaseEntity entity = get(clazz, StringUtil.toString(id));
if (entity != null) {
BeanUtils.setProperty(entity, SystemConstant.TABLE_STATUS, AbstractEntity.STATUS_LOGDEL);
}
this.saveOrUpdate(entity);
}

@Override
public void logDelById(Class clazz, List<String> ids) throws Exception {
List<BaseEntity> list = get(clazz, ids);
for (BaseEntity t : list) {
BeanUtils.setProperty(t, SystemConstant.TABLE_STATUS, AbstractEntity.STATUS_LOGDEL);
}

saveOrUpdate(list);
}

private <T extends BaseEntity> List<T> findByExample(@NotNull T example) {
Session session = this.sessionFactory.openSession();
Criteria criteria = session.createCriteria(example.getClass());

if (example != null) {
criteria.add(Example.create(example));
}
List list = criteria.list();
session.close();
return list;
}

/**
* 获取Session
*
* @return Session
* @author xiaojf 2015-5-9 8:35:08
*/
private Session getSession() {
return this.sessionFactory.getCurrentSession();
}
}

springboot 获取hibernate 的 SessionFactory