spring boot基于Mysql集成hibernate jpa【原创】

java技术文章

2018-10-28

53

0

今天跟大家说说spring boot怎么样集成hibernate jpa和其中一些注意事项。闲话不多说,直接上项目。

一、引入maven包

spring boot的maven包我就不在这里介绍了,只贴出hibernate的maven包:

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.data</groupId>
	<artifactId>spring-data-jpa</artifactId>
	<optional>true</optional>
	<exclusions>
		<exclusion>
			<artifactId>jcl-over-slf4j</artifactId>
			<groupId>org.slf4j</groupId>
		</exclusion>
	</exclusions>
</dependency>
<dependency>
	<groupId>org.hibernate</groupId>
	<artifactId>hibernate-entitymanager</artifactId>
	<optional>true</optional>
</dependency>
<dependency>
	<groupId>org.hibernate</groupId>
	<artifactId>hibernate-validator</artifactId>
	<optional>true</optional>
	<version>6.0.12.Final</version>
</dependency>
<dependency>
	<groupId>org.hibernate.validator</groupId>
	<artifactId>hibernate-validator-annotation-processor</artifactId>
</dependency>
<dependency>
		<groupId>mysql</groupId>
		<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
	<groupId>org.apache.commons</groupId>
	<artifactId>commons-dbcp2</artifactId>
</dependency>

二、hibernate和mysql配置项

我的项目配置文件是使用application.yml,所以直接在该文件中添加如下配置:

spring.datasource:
  continue-on-error: false
  separator: ;
  driver-class-name: com.mysql.cj.jdbc.Driver
  generate-unique-name: true
  url: jdbc:mysql://127.0.0.1:3306/poobase?useUnicode=true&characterEncoding=utf8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
  username: root
  password: 数据库密码
  tomcat.test-on-borrow: true
  tomcat.max-wait: 20000
  tomcat.max-active: 50
  tomcat.max-idle: 20
  tomcat.min-idle: 15
spring.jpa:
  database: MYSQL
  database-platform: org.hibernate.dialect.MySQLDialect
  properties.hibernate.dialect: org.hibernate.dialect.MySQL5Dialect
  hibernate.naming.physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
  hibernate.naming.implicit-strategy: org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl
  generate-ddl: false
  hibernate.ddl-auto: none
  properties.hibernate.current_session_context_class: org.springframework.orm.hibernate5.SpringSessionContext
  hibernate.use-new-id-generator-mappings: false
  open-in-view: true
  show-sql: true

如果你使用的是自定义配置的话,根据自己的自动配置类进行调整。

说明:

spring.jpa.hibernate.naming.physical-strategy:

hibernate升级到5.x以后,实体类和数据表的表名、列明需要指定转换策略,该项配置的作用是当实体类没有明确标明数据表名和列名时候的转换策略,我这里使用的是org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl,表示表名和列名不做任何转换。

ImplicitNamingStrategyJpaCompliantImpl:

默认的命名策略,兼容JPA 2.0的规范,不做任何转换。

三、启用hibernate jpa

在spring boot入口类中添加如下注解配置表示启用jpa配置项:

@ComponentScan(basePackages= {"com.mco"})
@EnableJpaRepositories(basePackages = {"com.mco"})
@EntityScan(basePackages = {"com.mco"})

四、DAO类连接数据源配置

/**
 * Project Name:mco.database
 * File Name:BaseDao.java
 * Package Name:com.mco.db
 * Date:2018年9月3日下午8:48:47
 * Copyright (c) 2018, 649445087@qq.com All Rights Reserved.
 *
*/

package com.mco.base.dao;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.metadata.ClassMetadata;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.mco.basic.exception.UncheckedException;
import com.mco.basic.model.Page;
import com.mco.basic.util.BeanUtils;
import com.mco.basic.util.CollectionUtils;

/**
 * ClassName:BaseDao <br/>
 * Function: TODO ADD FUNCTION. <br/>
 * Reason:	 TODO ADD REASON. <br/>
 * Date:     2018年9月3日 下午8:48:47 <br/>
 * @author   LUOFUJIA
 * @version  
 * @jdk version JDK 1.8
 * @see 	 
 */
public class HibernateBaseDao<T> {
    
    private final static Logger logger = LoggerFactory.getLogger(HibernateBaseDao.class);   
    
    @Autowired
    private EntityManagerFactory entityManagerFactory;
    
    private EntityManager entityManager;
    
    private CriteriaBuilder criteriaBuilder;
    
    private Class<T> classz;

    
    @SuppressWarnings("unchecked")
    public HibernateBaseDao(){
        classz = (Class<T>)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }
    
    public void setCriteriaBuilder(CriteriaBuilder criteriaBuilder) {
        
        this.criteriaBuilder = criteriaBuilder;
    }

    public void setEntityManager(EntityManager entityManager) {
        
        this.entityManager = entityManager;
    }

    public EntityManager getEntityManager() {
        if(entityManager==null) {
            entityManager = entityManagerFactory.createEntityManager();
        }
        return entityManager;
    }
       
    /**
     * 获取Hibernate的Session对象。
     * 
     * @return 返回Hibernate的Session对象。
     */
    public CriteriaBuilder getCriteriaBuilder(){
        //if(criteriaBuilder==null) {
            criteriaBuilder = entityManagerFactory.getCriteriaBuilder();
        //}
       return criteriaBuilder;
    }
    
    public SessionFactory getSessionFactory() {
        if (entityManagerFactory.unwrap(SessionFactory.class) == null) {
            throw new NullPointerException("factory is not a hibernate factory");
        }
        return entityManagerFactory.unwrap(SessionFactory.class);
    }
    
    /**
     * 
     * save:. <br/>
     * 保存实体  .<br/>
     * TODO.<br/>
     *
     * @author LUOFUJIA
     * @param entity
     * @jdk version JDK 1.8
     */
    public void save(T entity) {
        getEntityManager().persist(entity);
    }
    
    /**
     * 
     * merge:. <br/>
     * 更新实体.<br/>
     * TODO.<br/>
     *
     * @author LUOFUJIA
     * @param entity
     * @jdk version JDK 1.8
     */
    public void update(T entity) {
        getEntityManager().merge(entity);
    }
    
    
    
    public void remove(T entity) {
        getEntityManager().remove(entity);
    }
    
    
    public void remove(String id) {
        T entity = this.getById(id);
        this.remove(entity);
    }
    
    /**
     * 
     * getById:. <br/>
     * 根据id查询对应实体  .<br/>
     *
     * @author LUOFUJIA
     * @param id
     * @return
     * @jdk version JDK 1.8
     */
    @Transactional(readOnly=true)
    public T getById(String id) {
       CriteriaQuery<T> criteria =  getCriteriaBuilder().createQuery(classz);
       Root<T> root = criteria.from(classz);
       criteria.select(root);
       criteria.where( getCriteriaBuilder().equal( root.get("id"),id));
       return getEntityManager().createQuery( criteria ).getSingleResult();
    }
    
    /**
     * 
     * getAll:. <br/>
     * 查询当前实体所有数据.<br/>
     * TODO.<br/>
     *
     * @author LUOFUJIA
     * @return
     * @jdk version JDK 1.8
     */
    @Transactional(readOnly=true)
    public List<T> getAllList() {
        CriteriaQuery<T> criteria = getCriteriaBuilder().createQuery(classz);
        Root<T> root = criteria.from(classz);
        criteria.select( root );
        return getEntityManager().createQuery( criteria ).getResultList();
    }
    
    /**
     * 
     * getUniqueByCriteria:. <br/>
     * 根据CriteriaQuery查询一条数据  .<br/>
     * TODO.<br/>
     *
     * @author LUOFUJIA
     * @param criteria
     * @return
     * @jdk version JDK 1.8
     */
    @Transactional(readOnly=true)
    public T getUniqueByCriteria(CriteriaQuery<T> criteria) {
        return getEntityManager().createQuery( criteria ).getSingleResult();
    }
    
    /**
     * 
     * getListByCriteria:. <br/>
     * 根据CriteriaQuery查询数据列表  .<br/>
     * TODO.<br/>
     *
     * @author LUOFUJIA
     * @param criteria
     * @return
     * @jdk version JDK 1.8
     */
    @Transactional(readOnly=true)
    public List<T> getListByCriteria(CriteriaQuery<T> criteria){
        return getEntityManager().createQuery( criteria ).getResultList();
    }
    
    
    /**
     * 
     * getALLCount:. <br/>
     * @description  .<br/>
     * TODO.<br/>
     *
     * @author LUOFUJIA
     * @return
     * @jdk version JDK 1.8
     */
    @Transactional(readOnly=true)
    public Long getCount(CriteriaQuery<T> criteriaParams) {
        CriteriaBuilder builder = getCriteriaBuilder();
        CriteriaQuery<Long> criteria = builder.createQuery(Long.class);
        criteria.select(builder.count(criteria.from(classz)));
        if(criteriaParams.getRestriction()!=null) {
            criteria.where(criteriaParams.getRestriction());
        }
        return (Long)getEntityManager().createQuery(criteria).getSingleResult();
    }
    
    /**
     * 
     * getByPage:. <br/>
     * 查询分页实体列表  .<br/>
     *
     * @author LUOFUJIA
     * @param criteriaParams 查询条件
     * @param pageNo 页码
     * @param pageSize 页大小
     * @return
     * @jdk version JDK 1.8
     */
    @Transactional(readOnly=true)
    public Page<T> getByPage(CriteriaQuery<T> criteria,Integer pageNo,Integer pageSize){
        Long count = this.getCount(criteria);
//        CriteriaBuilder builder = getCriteriaBuilder();
//        CriteriaQuery<T> criteria = builder.createQuery(classz);
//        Root<T> root = criteria.from(classz);
//        criteria.select(root);
//        if(criteriaParams.getRestriction()!=null) {
//            criteria.where(criteriaParams.getRestriction());
//        }
//        if(criteriaParams.getOrderList()!=null) {
//            criteria.orderBy(criteriaParams.getOrderList());
//        }
//      Expression<String> path = root.get("lastName");
//      Expression<String> upper =critBuilder.upper(path);
//      Predicate ctfPredicate = critBuilder.like(upper,"%stringToFind%")
//      critQ.where(critBuilder.and(ctfPredicate));
//      em.createQuery(critQ.select(root)).getResultList();
        
        Page<T> page = new Page<T>(count.intValue(),pageNo,pageSize);
        TypedQuery<T> pageQuery = getEntityManager().createQuery(criteria);
        pageQuery.setFirstResult((page.getNumber()-1)*page.getSize());
        pageQuery.setMaxResults(pageSize);
        page.setContents(pageQuery.getResultList());
        return page;
    }
    
    
    /**
     * 获取实体类的主键名。
     * 
     * @return 返回实体类的主键名。
     */
    private String getIdName() {
        ClassMetadata meta = getClassMetadata();
        return meta.getIdentifierPropertyName();
    }
    
    
    @SuppressWarnings("deprecation")
    private ClassMetadata getClassMetadata() {
        Session session = getEntityManager().unwrap(Session.class);
        ClassMetadata classMetadata = session.getSessionFactory().getClassMetadata(classz);
        return classMetadata;
    }
    
    /**
     * 获取实体类的主键值。 
     * 
     * @param entity
     *            实体对象
     * @return 返回实体类的主键值。
     */
    @Transactional(readOnly=true)
    private Serializable getId(T entity) {
        return (Serializable) BeanUtils.getField(entity, getIdName());
    }
    
    /**
     * 
     * getByUnique:. <br/>
     * 根据某一字段获取当前实例对象  .<br/>
     * TODO.<br/>
     *
     * @author LUOFUJIA
     * @param fieldName
     * @param fieldValue
     * @return
     * @throws UncheckedException
     * @jdk version JDK 1.8
     */
    @Transactional(readOnly=true)
    public T findUnique(String fieldName,String fieldValue) throws UncheckedException{
        try {
            CriteriaBuilder builder  = this.getCriteriaBuilder();
            CriteriaQuery<T> criteriaQuery = builder.createQuery(classz);
            Root<T> root = criteriaQuery.from(classz);
            criteriaQuery.select(root);
            criteriaQuery.where(builder.equal(root.get(fieldName), fieldValue));
            List<T> resultList = this.getEntityManager().createQuery(criteriaQuery).getResultList();
            if(CollectionUtils.isNotEmpty(resultList)) {
                return resultList.get(0);
            }
            return null;
        }catch(Exception e) {
            logger.error("getByUnique error", e);
            throw new UncheckedException(e.getMessage());
        }
    }
    
    @Transactional(readOnly=true)
    public Boolean isUnique(T entity,String propNames) throws UncheckedException{
        try {
            if(StringUtils.isEmpty(propNames)) {
                throw new UncheckedException("isUnique params name propNames is null!");
            }
            String[] fieldNameList = propNames.split(",");
            CriteriaBuilder builder  = this.getCriteriaBuilder();
            CriteriaQuery<T> criteriaQuery = builder.createQuery(classz);
            Root<T> root = criteriaQuery.from(classz);
            criteriaQuery.select(root);
            List<Predicate> paramsList = new ArrayList<Predicate>();
            for(String fieldName:fieldNameList) {
                Predicate whereParams = builder.equal(root.get(fieldName), BeanUtils.getField(entity, fieldName));
                paramsList.add(whereParams);
            }
            String idName = getIdName();
            Serializable id = getId(entity);
            if (id != null) {
                Predicate whereParams = builder.notEqual(root.get(idName), id);
                paramsList.add(whereParams);
            }
            criteriaQuery.where(paramsList.toArray(new Predicate[paramsList.size()]));
            Integer size = this.getEntityManager().createQuery(criteriaQuery).getResultList().size();
            return size==0;
        }catch(Exception e) {
            logger.error("isUnique error", e);
            throw new UncheckedException(e.getMessage());
        }
    }
    
    /**
     * 
     * createHqlQuery:. <br/>
     * Hql执行Query .<br/>
     * TODO.<br/>
     *
     * @author LUOFUJIA
     * @param hql
     * @param params
     * @return
     * @jdk version JDK 1.8
     */
    @Transactional(readOnly=true)
    public Query createHqlQuery(String hql,List<Object> params) throws UncheckedException {
        try {
            Query query = this.getEntityManager().createQuery(hql);
            if(CollectionUtils.isNotEmpty(params)) {
                for(int i=0;i<params.size();i++) {
                    query.setParameter(i, params.get(i));
                }
            }
            return query;
        }catch(Exception e) {
            logger.error("createHqlQuery error", e);
            throw new UncheckedException(e.getMessage());
        }
    }
    
    
    /**
     * 执行count查询获得本次Hql查询所能获得的对象总数。<br/>
     * 本函数只能自动处理简单的hql语句,复杂的hql查询请另行编写count语句查询。
     * 
     * @param hql
     *            查询语句
     * @param values
     *            查询参数
     * @return 返回查询结果总数
     */
    @Transactional(readOnly=true)
    public Integer countHqlResult(String hql,List<Object> params) {
        String fromHql = hql;
        fromHql = "from " + StringUtils.substringAfter(fromHql, "from");
        fromHql = StringUtils.substringBefore(fromHql, "order by");
        String countHql = "select count(*) " + fromHql;
        int count = Integer.parseInt(createHqlQuery(countHql, params).getSingleResult().toString());
        return count;
    }
    
    /**
     * 
     * getByPage:. <br/>
     * 查询分页实体列表  .<br/>
     *
     * @author LUOFUJIA
     * @param criteriaParams 查询条件
     * @param pageNo 页码
     * @param pageSize 页大小
     * @return
     * @jdk version JDK 1.8
     */
    @SuppressWarnings("unchecked")
    @Transactional(readOnly=true)
    public Page<T> getByPage(String hql, Integer pageNo, Integer pageSize,List<Object> params){
        int count = this.countHqlResult(hql,params);
        Page<T> page = new Page<T>(count,pageNo,pageSize);
        Query query  = this.createHqlQuery(hql,params);
        query.setFirstResult((page.getNumber()-1)*page.getSize());
        query.setMaxResults(pageSize);
        page.setContents(query.getResultList());
        return page;
    }
    
    /**
     * 
     * createSqlQuery:. <br/>
     * Sql查询Query  .<br/>
     * TODO.<br/>
     *
     * @author LUOFUJIA
     * @param sql
     * @param params
     * @return
     * @throws UncheckedException
     * @jdk version JDK 1.8
     */
    @Transactional(readOnly=true)
    public Query createSqlQuery(String sql,List<Object> params) throws UncheckedException {
        try {
            Query query  = this.getEntityManager().createNativeQuery(sql);
            if(CollectionUtils.isNotEmpty(params)) {
                for(int i=0;i<params.size();i++) {
                    query.setParameter(i, params.get(i));
                }
            }
            return query;
        }catch(Exception e) {
            logger.error("createSqlQuery error", e);
            throw new UncheckedException(e.getMessage());
        }
    }
    
    
    /**
     * 
     * createSqlQuery:. <br/>
     * Sql查询Query  .<br/>
     * TODO.<br/>
     *
     * @author LUOFUJIA
     * @param sql
     * @param params
     * @return
     * @throws UncheckedException
     * @jdk version JDK 1.8
     */
    @SuppressWarnings("rawtypes")
    @Transactional(readOnly=true)
    public Query createSqlQuery(String sql,List<Object> params,Class classz) throws UncheckedException {
        try {
            Query query  = this.getEntityManager().createNativeQuery(sql,classz);
            if(CollectionUtils.isNotEmpty(params)) {
                for(int i=0;i<params.size();i++) {
                    query.setParameter(i, params.get(i));
                }
            }
            return query;
        }catch(Exception e) {
            logger.error("createSqlQuery error", e);
            throw new UncheckedException(e.getMessage());
        }
    }
    
    
    /**
     * 
     * createSqlQuery:. <br/>
     * Sql查询Query  .<br/>
     * TODO.<br/>
     *
     * @author LUOFUJIA
     * @param sql
     * @param params
     * @return
     * @throws UncheckedException
     * @jdk version JDK 1.8
     */
    @Transactional(readOnly=true)
    public Query createSqlQuery(String sql,List<Object> params,String resultMapping) throws UncheckedException {
        try {
            Query query  = this.getEntityManager().createNativeQuery(sql,resultMapping);
            if(CollectionUtils.isNotEmpty(params)) {
                for(int i=0;i<params.size();i++) {
                    query.setParameter(i, params.get(i));
                }
            }
            return query;
        }catch(Exception e) {
            logger.error("createSqlQuery error", e);
            throw new UncheckedException(e.getMessage());
        }
    }

}

五、hibernate CriteriaQuery查询实例:

/**
     * 
     * getByOrganId:. <br/>
     * @description  .<br/>
     * 根据机构id查询关联用户和职务.<br/>
     *
     * @author LUOFUJIA
     * @param organId 机构id
     * @param pageNo  页数
     * @param pageSize 页大小
     * @return Page<OrganUserRelation>
     * @throws UncheckedException
     * @jdk version JDK 1.8
     */
    @SuppressWarnings({"rawtypes", "unchecked" })
    @Transactional(readOnly = true)
    public Page<OrganUserRelation> getByOrganId(OrganUserRelation relation,Integer pageNo,Integer pageSize) throws UncheckedException{
        try{
            CriteriaBuilder builder = organUserRelationDao.getCriteriaBuilder();
            CriteriaQuery<OrganUserRelation> criteria = builder.createQuery(OrganUserRelation.class);
            Root<OrganUserRelation> root = criteria.from(OrganUserRelation.class);
            Join organJoin = root.join("organ");
            List<Predicate> whereList = new ArrayList<Predicate>();
            Predicate organCredential = builder.equal(organJoin.get("id"), relation.getOrgan().getId());
            whereList.add(organCredential);
            if(relation.getUser()!=null&&StringUtils.isNotEmpty(relation.getUser().getName())){
                Join userJoin = root.join("user");
                Expression<String> path = userJoin.get("name");
                Expression<String> upper =builder.upper(path);
                Predicate userCredential = builder.like(upper,"%"+relation.getUser().getName().trim()+"%");
                whereList.add(userCredential);
            }
            criteria.select(root);
            criteria.where(whereList.toArray(new Predicate[whereList.size()]));
            return organUserRelationDao.getByPage(criteria, pageNo, pageSize);
        }catch(Exception e){
            logger.error("OrganUserRelationService getByOrganId error", e);
            throw new UncheckedException(messageConfig.getString("dao.message.error.query"));
        }
    }

六、完成

欢迎访问:www.hongfu951.com博客,查看更多文章

发表评论

全部评论:0条

鸿福951

努力打造一个好用的webui

热评文章

推荐文章