JPA 使用criteria简单查询工具类方式

网友投稿 657 2022-09-08


JPA 使用criteria简单查询工具类方式

目录使用criteria简单查询工具类首先创建类并实现Specification接口新建ExpandCriterion接口使用criteria前提是dao接口必须实现JpaSpecificationExecutor接口打包JPA动态查询(CriteriaQuery) eq、ge、gt封装JPA动态查询(CriteriaQuery)EntityManager管理器,通过spring管理Page分页和结果封装类IBaseDao接口实现了BaseDaoImplIBaseDao接口

使用criteria简单查询工具类

以前用jpa写了一个条件筛选的查询数据如下,才知道那么渣渣,就是一个表,根据前端来筛选数据,写的如下

首先就是判断前端传来的参数就写了那么多,现在才发现是渣渣中的渣渣,而且还费时,用criteria很快就搞定

首先创建类并实现Specification接口

import java.util.ArrayList;

import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;

import javax.persistence.criteria.CriteriaQuery;

import javax.persistence.criteria.Predicate;

import javax.persistence.criteria.Root;

import org.springframework.data.jpa.domain.Specification;

public class ExpandCriteria implements Specification{

private List criterions = new ArrayList();

public Predicate toPredicate(Root root, CriteriaQuery query,

CriteriaBuilder builder) {

if (!criterions.isEmpty()) {

List predicates = new ArrayList();

for(ExpandCriterion c : criterions){

predicates.add(c.toPredicate(root, query,builder));

}

// 将所有条件用 and 联合起来

if (predicates.size() > 0) {

return builder.and(predicates.toArray(new Predicate[predicates.size()]));

}

}

return builder.conjunction();

}

/**

* 增加简单条件表达式

* @Methods Name add

* @Create In 2012-2-8 By lee

* @param expression0 void

*/

public void add(ExpandCriterion criterion){

if(criterion!=null){

criterions.add(criterion);

}

}

public static void main(String[] args) {

//使用示例Demo

// Criteria c = new Criteria();

// c.add(Restrictions.like("code", searchParam.getCode(), true));

// c.add(Restrictions.eq("level", searchParam.getLevel(), false));

// c.add(Restrictions.eq("mainStatus", searchParam.getMainStatus(), true));

// c.add(Restrictions.eq("flowStatus", searchParam.getFlowStatus(), true));

// c.add(Restrictions.eq("createUser.userName", searchParam.getCreateUser(), true));

// c.add(Restrictions.lte("submitTime", searchParam.getStartSubmitTime(), true));

// c.add(Restrictions.gte("submitTime", searchParam.getEndSubmitTime(), true));

// c.add(Restrictions.eq("needFollow", searchParam.getIsfollow(), true));

// c.add(Restrictions.ne("flowStatus", searchParam.getMainStatus() true));

// c.add(Restrictions.in("solveTeam.code",teamCodes, true));

// repository.findAll(c);

}

}

新建ExpandCriterion接口

import javax.persistence.criteria.CriteriaBuilder;

import javax.persistence.criteria.CriteriaQuery;

import javax.persistence.criteria.Predicate;

import javax.persistence.criteria.Root;

public interface ExpandCriterion {

public enum Operator {

EQ, NE, LIKE, GT, LT, GTE, LTE, AND, OR

}

public Predicate toPredicate(Root root, CriteriaQuery query,

CriteriaBuilder builder);

}

新建Restrictions.java

import java.util.Collection;

import org.springframework.util.StringUtils;

import com.sll.iot.dao.base.criteria.ExpandCriterion.Operator;

public class Restrictions {

/**

* 等于

* @param fieldName

* @param value

* @param ignoreNull

* @return

*/

public static SimpleExpression eq(String fieldName, Object value, boolean ignoreNull) {

if(StringUtils.isEmpty(value))return null;

return new SimpleExpression (fieldName, value, Operator.EQ);

}

/**

* 不等于

* @param fieldName

* @param value

* @param ignoreNull

* @return

*/

public static SimpleExpression ne(String fieldName, Object value, boolean ignoreNull) {

if(StringUtils.isEmpty(value))return null;

return new SimpleExpression (fieldName, value, Operator.NE);

}

/**

* 模糊匹配

* @param fieldName

* @param value

* @param ignoreNull

* @return

*/

public static SimpleExpression like(String fieldName, String value, boolean ignoreNull) {

if(StringUtils.isEmpty(value))return null;

return new SimpleExpression (fieldName, value, Operator.LIKE);

}

/**

* 大于

* @param fieldName

* @param value

* @param ignoreNull

* @return

*/

public static SimpleExpression gt(String fieldName, Object value, boolean ignoreNull) {

if(StringUtils.isEmpty(value))return null;

return new SimpleExpression (fieldName, value, Operator.GT);

}

/**

* 小于

* @param fieldName

* @param value

* @param ignoreNull

* @return

*/

public static SimpleExpression lt(String fieldName, Object value, boolean ignoreNull) {

if(StringUtils.isEmpty(value))return null;

return new SimpleExpression (fieldName, value, Operator.LT);

}

/**

* 大于等于

* @param fieldName

* @param value

* @param ignoreNull

* @return

*/

public static SimpleExpression lte(String fieldName, Object value, boolean ignoreNull) {

if(StringUtils.isEmpty(value))return null;

return new SimpleExpression (fieldName, value, Operator.GTE);

}

/**

* 小于等于

* @param fieldName

* @param value

* @param ignoreNull

* @return

*/

public static SimpleExpression gte(String fieldName, Object value, boolean ignoreNull) {

if(StringUtils.isEmpty(value))return null;

return new SimpleExpression (fieldName, value, Operator.LTE);

}

/**

* 并且

* @param criterions

* @return

*/

public static LogicalExpression and(ExpandCriterion... criterions){

return new LogicalExpression(criterions, Operator.AND);

}

/**

* 或者

* @param criterions

* @return

*/

public static LogicalExpression or(ExpandCriterion... criterions){

return new LogicalExpression(criterions, Operator.OR);

}

/**

* 包含于

* @param fieldName

* @param value

* @return

*/

@SuppressWarnings("rawtypes")

public static LogicalExpression in(String fieldName, Collection value, boolean ignoreNull) {

if(ignoreNull&&(value==null||value.isEmpty())){

return null;

}

SimpleExpression[] ses = new SimpleExpression[value.size()];

int i=0;

for(Object obj : value){

ses[i]=new SimpleExpression(fieldName,obj,Operator.EQ);

i++;

}

return new LogicalExpression(ses,Operator.OR);

}

新建SimpleExpression.java

import javax.persistence.criteria.CriteriaBuilder;

import javax.persistence.criteria.CriteriaQuery;

import javax.persistence.criteria.Expression;

import javax.persistence.criteria.Path;

import javax.persistence.criteria.Predicate;

import javax.persistence.criteria.Root;

public class SimpleExpression implements ExpandCriterion{

private String fieldName; //属性名

private Object value; //对应值

private Operator operator; //计算符

protected SimpleExpression(String fieldName, Object value, Operator operator) {

this.fieldName = fieldName;

this.value = value;

this.operator = operator;

}

public String getFieldName() {

return fieldName;

}

public Object getValue() {

return value;

}

public Operator getOperator() {

return operator;

}

@SuppressWarnings({ "rawtypes", "unchecked" })

public Predicate toPredicate(Root root, CriteriaQuery query,

CriteriaBuilder builder) {

Path expression = null;

if(fieldName.contains(".")){

String[] names = fieldName.split(".");

expression = root.get(names[0]);

for (int i = 1; i < names.length; i++) {

expression = expression.get(names[i]);

}

}else{

expression = root.get(fieldName);

}

switch (operator) {

case EQ:

return builder.equal(expression, value);

case NE:

return builder.notEqual(expression, value);

case LIKE:

return builder.like((Expression) expression, "%" + value + "%");

case LT:

return builder.lessThan(expression, (Comparable) value);

case GT:

return builder.greaterThan(expression, (Comparable) value);

case LTE:

return builder.lessThanOrEqualTo(expression, (Comparable) value);

case GTE:

return builder.greaterThanOrEqualTo(expression, (Comparable) value);

default:

return null;

}

}

}

LogicalExpression.java

import java.util.ArrayList;

import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;

import javax.persistence.criteria.CriteriaQuery;

import javax.persistence.criteria.Predicate;

import javax.persistence.criteria.Root;

public class LogicalExpression implements ExpandCriterion {

private ExpandCriterion[] criterion; // 逻辑表达式中包含的表达式

private Operator operator; //计算符

public LogicalExpression(ExpandCriterion[] criterions, Operator operator) {

this.criterion = criterions;

this.operator = operator;

}

public Predicate toPredicate(Root root, CriteriaQuery query,

CriteriaBuilder builder) {

List predicates = new ArrayList();

for(int i=0;i

predicates.add(this.criterion[i].toPredicate(root, query, builder));

}

switch (operator) {

case OR:

return builder.or(predicates.toArray(new Predicate[predicates.size()]));

default:

return null;

}

}

}

使用criteria前提是dao接口必须实现JpaSpecificationExecutor接口

改造如下

//条件查询

@Override

public Paging query(Paging paging,String channelName,String operator) {

Pageable pageReq = new PageRequest(paging.getCurrentPage()-1, paging.getPageSize());

Page pageChanel=null;

ExpandCriteria criteria = new ExpandCriteria();

if(StringUtil.isNotEmpty(channelName)){

criteria.add(Restrictions.like("name", channelName, false));

}

if(StringUtil.isNotEmpty(operator)){

criteria.add(Restrictions.eq("operator",Operator.valueOf(operator), false));

}

pageChanel=channelRepository.findAll(criteria, pageReq);

if(pageChanel!=null){

paging.setTotalCount((int)pageChanel.getTotalElements());

paging.setData(pageChanel.getContent());

paging.setTotalPage(pageChanel.getTotalPages());

}

return paging;

}

都不用在dao接口写什么东西

使用方法就是demo

public static void main(String[] args) {

//使用示例Demo

// Criteria c = new Criteria();

// c.add(Restrictions.like("code", searchParam.getCode(), true));

// c.add(Restrictions.eq("level", searchParam.getLevel(), false));

// c.add(Restrictions.eq("mainStatus", searchParam.getMainStatus(), true));

// c.add(Restrictions.eq("flowStatus", searchParam.getFlowStatus(), true));

// c.add(Restrictions.eq("createUser.userName", searchParam.getCreateUser(), true));

// c.add(Restrictions.lte("submitTime", searchParam.getStartSubmitTime(), true));

// c.add(Restrictions.gte("submitTime", searchParam.getEndSubmitTime(), true));

// c.add(Restrictions.eq("needFollow", searchParam.getIsfollow(), true));

// c.add(Restrictions.ne("flowStatus", searchParam.getMainStatus() true));

// c.add(Restrictions.in("solveTeam.code",teamCodes, true));

// repository.findAll(c);

}

打包JPA动态查询(CriteriaQuery) eq、ge、gt

封装JPA动态查询(CriteriaQuery)

JPA动态查询(CriteriaQuery)封装的一段代码:

package com.platform.framework.dao.jpa;

import java.io.Serializable;

import java.util.ArrayList;

import java.util.Collection;

import java.util.Date;

import java.util.HashMap;

import java.util.Iterator;

import java.util.List;

import java.util.Map;

import javax.persistence.EntityManager;

import javax.persistence.criteria.CriteriaBuilder;

import javax.persistence.criteria.CriteriaBuilder.In;

import javax.persistence.criteria.CriteriaQuery;

import javax.persistence.criteria.Order;

import javax.persistence.criteria.Predicate;

import javax.persistence.criteria.Root;

import org.apache.log4j.Logger;

/**

* Query基类

*

* @describe:封装JPA CriteriaBuilder查询条件

* @author:lry

* @since:2014-05-23

*/

@SuppressWarnings({ "unused", "unchecked", "rawtypes", "null", "hiding" })

public class Query implements Serializable {

private static final long serialVersionUID = 5064932771068929342L;

private static Logger log = Logger.getLogger(Query.class);

private EntityManager entityManager;

/** 要查询的模型对象 */

private Class clazz;

/** 查询条件列表 */

private Root from;

private List predicates;

private CriteriaQuery criteriaQuery;

private CriteriaBuilder criteriaBuilder;

/** 排序方式列表 */

private List orders;

/** 关联模式 */

private Map subQuery;

private Map linkQuery;

private String projection;

/** 或条件 */

private List orQuery;

private String groupBy;

private Query() {

}

private Query(Class clazz, EntityManager entityManager) {

this.clazz = clazz;

this.entityManager = entityManager;

this.criteriaBuilder = this.entityManager.getCriteriaBuilder();

this.criteriaQuery = criteriaBuilder.createQuery(this.clazz);

this.from = criteriaQuery.from(this.clazz);

this.predicates = new ArrayList();

this.orders = new ArrayList();

}

/** 通过类创建查询条件 */

public static Query forClass(Class clazz, EntityManager entityManager) {

return new Query(clazz, entityManager);

}

/** 增加子查询 */

private void addSubQuery(String propertyName, Query query) {

if (this.subQuery == null)

this.subQuery = new HashMap();

if (query.projection == null)

throw new RuntimeException("子查询字段未设置");

this.subQuery.put(propertyName, query);

}

private void addSubQuery(Query query) {

addSubQuery(query.projection, query);

}

/** 增关联查询 */

public void addLinkQuery(String propertyName, Query query) {

if (this.linkQuery == null)

this.linkQuery = new HashMap();

this.linkQuery.put(propertyName, query);

}

/** 相等 */

public void eq(String propertyName, Object value) {

if (isNullOrEmpty(value))

return;

this.predicates.add(criteriaBuilder.equal(from.get(propertyName), value));

}

private boolean isNullOrEmpty(Object value) {

if (value instanceof String) {

return value == null || "".equals(value);

}

return value == null;

}

public void or(List propertyName, Object value) {

if (isNullOrEmpty(value))

return;

if ((propertyName == null) || (propertyName.size() == 0))

return;

Predicate predicate = criteriaBuilder.or(criteriaBuilder.equal(from.get(propertyName.get(0)), value));

for (int i = 1; i < propertyName.size(); ++i)

predicate = criteriaBuilder.or(predicate, criteriaBuilder.equal(from.get(propertyName.get(i)), value));

this.predicates.add(predicate);

}

public void orLike(List propertyName, String value) {

if (isNullOrEmpty(value) || (propertyName.size() == 0))

return;

if (value.indexOf("%") < 0)

value = "%" + value + "%";

Predicate predicate = criteriaBuilder.or(criteriaBuilder.like(from.get(propertyName.get(0)), value.toString()));

for (int i = 1; i < propertyName.size(); ++i)

predicate = criteriaBuilder.or(predicate, criteriaBuilder.like(from.get(propertyName.get(i)), value));

this.predicates.add(predicate);

}

/** 空 */

public void isNull(String propertyName) {

this.predicates.add(criteriaBuilder.isNull(from.get(propertyName)));

}

/** 非空 */

public void isNotNull(String propertyName) {

this.predicates.add(criteriaBuilder.isNotNull(from.get(propertyName)));

}

/** 不相等 */

public void notEq(String propertyName, Object value) {

if (isNullOrEmpty(value)) {

return;

}

this.predicates.add(criteriaBuilder.notEqual(from.get(propertyName), value));

}

/**

* not in

*

* @param propertyName

* 属性名称

* @param value

* 值集合

*/

public void notIn(String propertyName, Collection value) {

if ((value == null) || (value.size() == 0)) {

return;

}

Iterator iterator = value.iterator();

In in = criteriaBuilder.in(from.get(propertyName));

while (iterator.hasNext()) {

in.value(iterator.next());

}

this.predicates.add(criteriaBuilder.not(in));

}

/**

* 模糊匹配

*

* @param propertyName

* 属性名称

* @param value

* 属性值

*/

public void like(String propertyName, String value) {

if (isNullOrEmpty(value))

return;

if (value.indexOf("%") < 0)

value = "%" + value + "%";

this.predicates.add(criteriaBuilder.like(from.get(propertyName), value));

}

/**

* 时间区间查询

*

* @param propertyName

* 属性名称

* @param lo

* 属性起始值

* @param go

* 属性结束值

*/

public void between(String propertyName, Date lo, Date go) {

if (!isNullOrEmpty(lo) && !isNullOrEmpty(go)) {

this.predicates.add(criteriaBuilder.between(from.get(propertyName), lo, go));

}

// if (!isNullOrEmpty(lo) && !isNullOrEmpty(go)) {

// this.predicates.add(criteriaBuilder.lessThan(from.get(propertyName),

// new DateTime(lo).toString()));

// }

// if (!isNullOrEmpty(go)) {

// this.predicates.add(criteriaBuilder.greaterThan(from.get(propertyName),

// new DateTime(go).toString()));

// }

}

public void between(String propertyName, Number lo, Number go) {

if (!(isNullOrEmpty(lo)))

ge(propertyName, lo);

if (!(isNullOrEmpty(go)))

le(propertyName, go);

}

/**

* 小于等于

*

* @param propertyName

* 属性名称

* @param value

* 属性值

*/

public void le(String propertyName, Number value) {

if (isNullOrEmpty(value)) {

return;

}

this.predicates.add(criteriaBuilder.le(from.get(propertyName), value));

}

/**

* 小于

*

* @param propertyName

* 属性名称

* @param value

* 属性值

*/

public void lt(String propertyName, Number value) {

if (isNullOrEmpty(value)) {

return;

}

this.predicates.add(criteriaBuilder.lt(from.get(propertyName), value));

}

/**

* 大于等于

*

* @param propertyName

* 属性名称

* @param value

* 属性值

*/

public void ge(String propertyName, Number value) {

if (isNullOrEmpty(value)) {

return;

}

this.predicates.add(criteriaBuilder.ge(from.get(propertyName), value));

}

/**

* 大于

*

* @param propertyName

* 属性名称

* @param value

* 属性值

*/

public void gt(String propertyName, Number value) {

if (isNullOrEmpty(value)) {

return;

}

this.predicates.add(criteriaBuilder.gt(from.get(propertyName), value));

}

/**

* in

*

* @param propertyName

* 属性名称

* @param value

* 值集合

*/

public void in(String propertyName, Collection value) {

if ((value == null) || (value.size() == 0)) {

return;

}

Iterator iterator = value.iterator();

In in = criteriaBuilder.in(from.get(propertyName));

while (iterator.hasNext()) {

in.value(iterator.next());

}

this.predicates.add(in);

}

/** 直接添加JPA内部的查询条件,用于应付一些复杂查询的情况,例如或 */

public void addCriterions(Predicate predicate) {

this.predicates.add(predicate);

}

/**

* 创建查询条件

*

* @return JPA离线查询

*/

public CriteriaQuery newCriteriaQuery() {

criteriaQuery.where(predicates.toArray(new Predicate[0]));

if (!isNullOrEmpty(groupBy)) {

criteriaQuery.groupBy(from.get(groupBy));

}

if (this.orders != null) {

criteriaQuery.orderBy(orders);

}

addLinkCondition(this);

return criteriaQuery;

}

private void addLinkCondition(Query query) {

Map subQuery = query.linkQuery;

if (subQuery == null)

return;

for (Iterator queryIterator = subQuery.keySet().iterator(); queryIterator.hasNext();) {

String key = (String) queryIterator.next();

Query sub = (Query) subQuery.get(key);

from.join(key);

criteriaQuery.where(sub.predicates.toArray(new Predicate[0]));

addLinkCondition(sub);

}

}

public void addOrder(String propertyName, String order) {

if (order == null || propertyName == null)

return;

if (this.orders == null)

this.orders = new ArrayList();

if (order.equalsIgnoreCase("asc"))

this.orders.add(criteriaBuilder.asc(from.get(propertyName)));

else if (order.equalsIgnoreCase("desc"))

this.orders.add(criteriaBuilder.desc(from.get(propertyName)));

}

public void setOrder(String propertyName, String order) {

this.orders = null;

addOrder(propertyName, order);

}

public Class getModleClass() {

return this.clazz;

}

public String getProjection() {

return this.projection;

}

public void setProjection(String projection) {

this.projection = projection;

}

public Class getClazz() {

return this.clazz;

}

public List getOrders() {

return orders;

}

public void setOrders(List orders) {

this.orders = orders;

}

public EntityManager getEntityManager() {

return this.entityManager;

}

public void setEntityManager(EntityManager em) {

this.entityManager = em;

}

public Root getFrom() {

return from;

}

public List getPredicates() {

return predicates;

}

public void setPredicates(List predicates) {

this.predicates = predicates;

}

public CriteriaQuery getCriteriaQuery() {

return criteriaQuery;

}

public CriteriaBuilder getCriteriaBuilder() {

return criteriaBuilder;

}

public void setFetchModes(List fetchField, List fetchMode) {

}

public String getGroupBy() {

return groupBy;

}

public void setGroupBy(String groupBy) {

this.groupBy = groupBy;

}

}

xmlns:xsi="http://w3.org/2001/XMLSchema-instance" xmlns:p="http://springframework.org/schema/p"

xmlns:tx="http://springframework.org/schema/tx" xmlns:context="http://springframework.org/schema/context"

xmlns:util="http://springframework.org/schema/util"

xmlns:aop="http://springframework.org/schema/aop"

xsi:schemaLocation="

http://springframework.org/schema/beans

http://springframework.org/schema/beans/spring-beans-3.1.xsd

http://springframework.org/schema/tx

http://springframework.org/schema/tx/spring-tx-3.1.xsd

http://springframework.org/schema/context

http://springframework.org/schema/context/spring-context-3.1.xsd

http://springframework.org/schema/aop

http://springframework.org/schema/aop/spring-aop.xsd

http://springframework.org/schema/util

http://springframework.org/schema/util/spring-util-3.1.xsd">

class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"

p:packagesToScan="com.**.model" p:dataSource-ref="dataSource"

p:jpaVendorAdapter-ref="hibernateVendor" p:jpaPropertyMap-ref="jpaPropertyMap"/>

class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"

p:database="MYSQL" p:showSql="true" p:generateDdl="true"

p:databasePlatform="org.hibernate.dialect.MySQLDialect" />

insert

update

delete

expression="

execution(* com.*.dao.*.*(..))||

execution(* com.*.service.impl.*.*(..))||

execution(* com.*.*.dao.*.*(..))||

execution(* com.*.*.service.impl.*.*(..))||

execution(* com.*.*.*.dao.*.*(..))||

execution(* com.*.*.*.service.impl.*.*(..))||

execution(* com.*.*.*.*.dao.*.*(..))||

execution(* com.*.*.*.*.service.impl.*.*(..))||

execution(* com.*.*.*.*.*.dao.*.*(..))||

execution(* com.*.*.*.*.*.service.impl.*.*(..))||

execution(* com.*.*.*.*.*.*.dao.*.*(..))||

execution(* com.*.*.*.*.*.*.service.impl.*.*(..))||

execution(* com.platform.framework.dao.jpa.BaseDaoImpl.*(..))"/>

package com.platform.framework.dao.jpa;

import javax.persistence.EntityManager;

import javax.persistence.EntityManagerFactory;

import javax.persistence.EntityTransaction;

import org.apache.log4j.Logger;

import org.aspectj.lang.ProceedingJoinPoint;

import org.aspectj.lang.Signature;

/**

* @describe JPA事务管理

* @author lry

* @since:2014-05-23

*

*/

public class TransactionHandler {

private static final Logger log = Logger

.getLogger(TransactionHandler.class);

private String[] txmethod;// 配置事务的传播特性方法

private EntityManagerFactory entityManagerFactory;// JPA工厂

public Object exec(ProceedingJoinPoint point) throws Throwable {

Signature signature = point.getSignature();

log.debug(point.getTarget().getClass().getName() + "."

+ signature.getName() + "()");

Boolean isTransaction = false;

for (String method : txmethod) {

if (signature.getName().startsWith(method)) {// 以method开头的方法打开事务

isTransaction = true;

break;

}

}

// JPA->Hibernate

if (point.getTarget() instanceof EntityManagerFactoryProxy) {

// 获得被代理对象

EntityManagerFactoryProxy emfp = (EntityManagerFactoryProxy) point

.getTarget();

EntityManager em = emfp.getEntityManager();

if (em != null) {// 如果对象已经有em了就不管

return point.proceed();

} else {

em = entityManagerFactory.createEntityManager();

}

log.debug("JPA->Hibernate open connection...");

if (isTransaction) {

EntityTransaction t = null;

try {

// 打开连接并开启事务

log.debug("JPA->Hibernate begin transaction...");

t = em.getTransaction();

if (!t.isActive())

t.begin();

emfp.setEntityManager(em);

Object obj = point.proceed();

// 提交事务

log.debug("JPA->Hibernate commit...");

t.commit();

return obj;

} catch (Exception e) {

if (t != null) {

log.debug("JPA->Hibernate error...,rollback..."

+ e.getMessage());

t.rollback();

}

e.printStackTrace();

throw e;

} finally {

if (em != null && em.isOpen()) {// 关闭连接

em.close();

log.debug("JPA->Hibernate close connection...");

}

emfp.setEntityManager(null);

}

} else {

try {

emfp.setEntityManager(em);

return point.proceed();

} catch (Exception e) {

log.debug("JPA->Hibernate error..." + e.getMessage());

e.printStackTrace();

throw e;

} finally {

if (em != null && em.isOpen()) {// 关闭连接

em.close();

log.debug("JPA->Hibernate close connection...");

}

emfp.setEntityManager(null);

}

}

} else {

return point.proceed();

}

}

public String[] getTxmethod() {

return txmethod;

}

public void setTxmethod(String[] txmethod) {

this.txmethod = txmethod;

}

public void setEntityManagerFactory(

EntityManagerFactory entityManagerFactory) {

this.entityManagerFactory = entityManagerFactory;

}

}

EntityManager管理器,通过spring管理

package com.platform.framework.dao.jpa;

import java.util.Collection;

import javax.persistence.EntityManager;

import javax.persistence.EntityManagerFactory;

/**

* EntityManager管理器

*

* @author:yangjian1004

* @since:2011-11-30 16:14:24 AM

*/

public class EntityManagerFactoryProxy {

private static ThreadLocal emThreadLocal = new ThreadLocal();

private static EntityManagerFactory emf;

public void setEmf(EntityManagerFactory emf) {

EntityManagerFactoryProxy.emf = emf;

}

public static EntityManagerFactory getEmf() {

return emf;

}

public EntityManager getEntityManager() {

return emThreadLocal.get();

}

public void setEntityManager(EntityManager em) {

emThreadLocal.set(em);

}

/**

* 创建查询条件

*

* @param name

* 字段名称

* @param values

* 字段值

*/

public String createInCondition(String name, Collection values) {

if (values == null || values.size() == 0) {

return "1<>1";

}

StringBuffer sb = new StringBuffer();

sb.append(name + " in(");

for (String id : values) {

sb.append("'" + id + "',");

}

String hsqlCondition = sb.substring(0, sb.length() - 1) + ")";

return hsqlCondition;

}

}

Page分页和结果封装类

package com.platform.framework.dao.jpa;

import java.io.Serializable;

import java.util.ArrayList;

import java.util.List;

/**

* Page基类

*

* @describe:分页

*/

public class Page implements Serializable {

private static final long serialVersionUID = 665620345605746930L;

/** 总条数 */

private int count;

/** 页码 */

private int pageNo;

/** 每页显示多少条 */

private int rowsPerPage;

/** 总页数 */

private int totalPageCount;

/** 起始条数 */

private int firstRow;

/** 结束条数 */

private int lastRow;

/** 查询结果集合形式的结果 */

private List result;

/** 查询结果对象形式的结果 */

public Object obj;

public Integer code; // 返回码

private boolean success = true;

private String message;

public Page() {

}

public Page(List list) {

this(list.size(), 1, list.size(), list);

}

public Page(int count, int pageNo, int rowsPerPage, List result) {

if (rowsPerPage < 1) {

rowsPerPage = 1;

}

this.count = count;

this.pageNo = pageNo;

this.result = result;

this.rowsPerPage = rowsPerPage;

if (this.result == null)

this.result = new ArrayList();

totalPageCount = count / rowsPerPage;

if (count - (count / rowsPerPage) * rowsPerPage > 0)

totalPageCount++;

if (count == 0) {

totalPageCount = 0;

pageNo = 0;

}

firstRow = (pageNo - 1) * rowsPerPage + 1;

if (count == 0) {

firstRow = 0;

}

lastRow = (pageNo) * rowsPerPage;

if (lastRow > count) {

lastRow = count;

}

}

/** 返回每页的条数 */

public int getCount() {

return count;

}

public List getResult() {

return result;

}

public int getPageNo() {

return pageNo;

}

/** 返回每页的条数 */

public int getRowsPerPage() {

return rowsPerPage;

}

/** 返回总的页数 */

public int getTotalPageCount() {

return totalPageCount;

}

public void setPageNo(int pageNo) {

this.pageNo = pageNo;

}

public void setRowsPerPage(int rowsPerPage) {

this.rowsPerPage = rowsPerPage;

}

public int getFirstRow() {

return firstRow;

}

public int getLastRow() {

return lastRow;

}

public void setFirstRow(int firstRow) {

this.firstRow = firstRow;

}

public void setLastRow(int lastRow) {

this.lastRow = lastRow;

}

public void setCount(int count) {

this.count = count;

}

public void setTotalPageCount(int totalPageCount) {

this.totalPageCount = totalPageCount;

}

public void setResult(List result) {

this.result = result;

}

public Object getObj() {

return obj;

}

public void setObj(Object obj) {

this.obj = obj;

}

public boolean isSuccess() {

return success;

}

public void setSuccess(boolean success) {

this.success = success;

}

public String getMessage() {

return message;

}

public void setMessage(String message) {

this.message = message;

}

/**

* 计算起始条数

*/

public statibDPaBc int calc(int pageNo, int rowsPerPage, int count) {

if (pageNo <= 0)

pageNo = 1;

if (rowsPerPage <= 0)

rowsPerPage = 10;

// 当把最后一页数据删除以后,页码会停留在最后一个上必须减一

int totalPageCount = count / rowsPerPage;

if (pageNo > totalPageCount && (count % rowsPerPage == 0)) {

pageNo = totalPageCount;

}

if (pageNo - totalPageCount > 2) {

pageNo = totalPageCount + 1;

}

int firstRow = (pageNo - 1) * rowsPerPage;

if (firstRow < 0) {

firstRow = 0;

}

return firstRow;

}

}

IBaseDao接口实现了BaseDaoImpl

package com.platform.framework.dao.jpa;

import java.io.Serializable;

import java.util.List;

import javax.persistence.EntityManager;

import javax.persistence.criteria.CriteriaQuery;

import javax.persistence.criteria.Predicate;

import javax.persistence.criteria.Selection;

import javax.persistence.metamodel.EntityType;

import org.apache.log4j.Logger;

import com.google.common.base.Strings;

/**

* IBaseDao接口实现了BaseDaoImpl类

*/

@SuppressWarnings({ "unchecked", "rawtypes" })

public class BaseDaoImpl extends EntityManagerFactoryProxy implements IBaseDao {

private static Logger log = Logger.getLogger(BaseDaoImpl.class);

/** 每次批量操作数 */

private int batchSize = 50;

/** 设置每次操作数 */

public void setBatchSize(int batchSize) {

this.batchSize = batchSize;

}

public E get(Class clazz, Serializable id) {

return (E) getEntityManager().find(clazz, id);

}

/**

* 插入记录

*

* @param entity

* 要插入的记录

*/

public void insert(Object entity) {

if (entity instanceof List) {

insertList((List) entity);

return;

} else if (entity instanceof Object[]) {

return;

}

try {

getEntityManager().persist(entity);

} catch (Exception e) {

e.printStackTrace();

}

}

/**

* 批量增加

*

* @param list

* 要新增的数据

*/

public void insertList(List list) {

EntityManager entityManager = getEntityManager();

if (list == null || list.size() == 0) {

return;

}

int i = 0;

for (Object o : list) {

insert(o);

if (i % batchSize == 0) {

entityManager.flush();

}

i++;

}

log.debug(list.get(0).getClass() + "批量增加数据" + i + "条");

}

/**

* 更新记录

*

* @param entity

* 要更新的记录

*/

public void update(Object entity) {

if (entity instanceof List) {

this.updateList((List) entity);

return;

}

getEntityManager().merge(entity);

}

/** 更新list */

public void updateList(List list) {

for (Object entity : list) {

this.update(entity);

}

}

/**

* 删除记录

*

* @param entity

* 要删除的记录

*/

public void delete(Object entity) {

if (entity instanceof List) {

List list = (List) entity;

for (Object o : list) {

getEntityManager().remove(o);

}

} else {

getEntityManager().remove(entity);

}

}

public List query(String jpql) {

return getEntityManager().createQuery(jpql).getResultList();

}

public Integer updateJpql(String jpql) {

return getEntityManager().createQuery(jpql).executeUpdate();

}

public Integer updateSql(String sql) {

return getEntityManager().createNativeQuery(sql).executeUpdate();

}

public List queryBySql(String sql) {

return getEntityManager().createNativeQuery(sql).getResultList();

}

/**

* 查询记录

*

* @param clazz

* 要查询的实体类

* @param hqlCondition

* 查询条件

*/

public List query(Class clazz, String hqlCondition) {

return getEntityManager().createQuery("select t from " + clazz.getName() + " as t where " + hqlCondition)

.getResultList();

}

public void delete(Class entity, String jpqlCondition) {

if (Strings.isNullOrEmpty(jpqlCondition)) {

jpqlCondition = "1=1";

}

int no = updateJpql("delete " + entity.getName() + " where " + jpqlCondition);

log.debug(entity.getName() + "删除" + no + "条数据");

}

/**

* 根据ids删除数据

*

* @param entity

* 删除实体类

* @param ids

* 删除条件

*/

public void delete(Class entity, List ids) {

String idName = getIdName(entity, getEntityManager());

StringBuffer sb = new StringBuffer();

sb.append(idName + " in(");

for (int i = 0; i < ids.size(); i++) {

sb.append("'" + ids.get(i) + "',");

}

String jpqlCondition = sb.substring(0, sb.length() - 1) + ")";

delete(entity, jpqlCondition);

}

public List query(String jpql, int firstResult, int maxResults) {

List result = getEntityManager().createQuery(jpql).setFirstResult(firstResult).setMaxResults(maxResults)

.getResultList();

return result;

}

public List queryBySql(String sql, int firstResult, int maxResults) {

return getEntityManager().createNativeQuery(sql).setFirstResult(firstResult).setMaxResults(maxResults)

.getResultList();

}

public List queryAll(Class clazz) {

CriteriaQuery criteriaQuery = getEntityManager().getCriteriaBuilder().createQuery(clazz);

criteriaQuery.from(clazz);

return getEntityManager().createQuery(criteriaQuery).getResultList();

}

public Page queryPageByJpql(String jpql, int pageNo, int rowsPerPage) {

if (pageNo <= 0)

pageNo = 1;

if (rowsPerPage <= 0)

rowsPerPage = 7;

log.debug("-----开始查询,页码:" + pageNo + ",每页显示:" + rowsPerPage + "----");

String countJpql = "select count(*) from (" + jpql + ")";

int count = getCount(countJpql).intValue();

// 当把最后一页数据删除以后,页码会停留在最后一个上必须减一

int totalPageCount = count / rowsPerPage;

if (pageNo > totalPageCount && (count % rowsPerPage == 0)) {

pageNo = totalPageCount;

}

if (pageNo - totalPageCount > 2) {

pageNo = totalPageCount + 1;

}

int firstResult = (pageNo - 1) * rowsPerPage;

if (firstResult < 0) {

firstResult = 0;

}

List result = getEntityManager().createQuery(jpql).setFirstResult(firstResult).setMaxResults(rowsPerPage)

.getResultList();

return new Page(count, pageNo, rowsPerPage, result);

}

public Long getCount(String jpql) {

return (Long) getEntityManager().createQuery(jpql).getResultList().get(0);

}

/***

*

* @Method updateJpql

* @Description 根据传入的带有占位符的sql语句, 做增删改操作 例如

* updateJpql("update user t set t.name=? where t.id=?"

* ,{[zhongxiang],[23]})

* @Author 钟翔/zhongxiang

* @Date 2012-8-9 下午3:38:35

* @param jpql

* 占位符式的sql

* @param paramList

* list里面装有[zhongxiang , 23]

*/

public void updateJpql(String jpql, List paramList) {

javax.persistence.Query query = getEntityManager().createQuery(jpql);

for (int i = 0; i < paramList.size(); i++) {

query.setParameter(i + 1, paramList.get(i));

}

query.executeUpdate();

}

/**

* 统计记录

*

* @param query

* 统计条件

*/

public Long getCount(Query query) {

Selection selection = query.getCriteriaQuery().getSelection();

query.getCriteriaQuery().select(query.getCriteriaBuilder().count(query.getFrom()));

Long count = (Long) getEntityManager().createQuery(query.newCriteriaQuery()).getResultList().get(0);

query.getCriteriaQuery().select(selection);

return count;

}

/**

* 分页查询

*

* @param query

* 查询条件

* @param pageNo

* 页号

* @param rowsPerPage

* 每页显示条数

*/

public Page queryPage(Query query, int pageNo, int rowsPerPage) {

if (pageNo <= 0)

pageNo = 1;

if (rowsPerPage <= 0)

rowsPerPage = 7;

log.debug(query.getClazz() + "-----开始查询,页码:" + pageNo + ",每页显示:" + rowsPerPage + "----");

log.debug("查询条件:");

for (Predicate cri : query.getPredicates())

log.debug(cri);

int count = getCount(query).intValue();

// 当把最后一页数据删除以后,页码会停留在最后一个上必须减一

int totalPageCount = count / rowsPerPage;

if (pageNo > totalPageCount && (count % rowsPerPage == 0)) {

pageNo = totalPageCount;

}

if (pageNo - totalPageCount > 2) {

pageNo = totalPageCount + 1;

}

int firstResult = (pageNo - 1) * rowsPerPage;

if (firstResult < 0) {

firstResult = 0;

}

List result = getEntityManager().createQuery(query.newCriteriaQuery()).setFirstResult(firstResult)

.setMaxResults(rowsPerPage).getResultList();

return new Page(count, pageNo, rowsPerPage, result);

}

/**

* 根据query查找记录

*

* @param query

* 查询条件

* @param firstResult

* 起始行

* @param maxResults

* 结束行

*/

public List query(Query query, int firstResult, int maxResults) {

List result = getEntityManager().createQuery(query.newCriteriaQuery()).setFirstResult(firstResult)

.setMaxResults(maxResults).getResultList();

return result;

}

/**

* 根据query查找记录

*

* @param query

* 查询条件

*/

public List query(Query query) {

return getEntityManager().createQuery(query.newCriteriaQuery()).getResultList();

}

/**

* 获得主键名称

*

* @param clazz

* 操作是实体对象

* @param EntityManager

* jpa的entityManager工厂

* @return 初建名称

* */

public static String getIdName(Class clazz, EntityManager entityManager) {

EntityType entityType = entityManager.getMetamodel().entity(clazz);

return entityType.getId(entityType.getIdType().getJavaType()).getName();

}

}

IBaseDao接口

package com.platform.framework.dao.jpa;

import java.io.Serializable;

import java.util.List;

import javax.persistence.EntityManager;

/**

* IBaseDao基类

*

* @describe:系统基础JPA Dao接口

*/

@SuppressWarnings({ "rawtypes" })

public interface IBaseDao {

public EntityManager getEntityManager();

public E get(Class clazz, Serializable id);

/**

* 插入记录

*

* @param entity

* 要插入的记录

*/

public void insert(Object entity);

/**

* 更新记录

*

* @param entity

* 要更新的记录

*/

public void update(Object entity);

/** 更新list */

public void updateList(List list);

/**

* 删除记录

*

* @param entity

* 要删除的记录

*/

public void delete(Object entity);

/**

* 删除记录

*

* @param entity

* 要删除的记录

*/

public void delete(Class entity, List ids);

/**

* 删除记录

http:// *

* @param entity

* 要删bDPaB除的记录

*/

public void delete(Class entity, String jpqlCondition);

/**

* 统计记录

*

* @param query

* 统计条件

*/

public Long getCount(Query query);

public Long getCount(String jpql);

/**

* 分页查询

*

* @param query

* 查询条件

* @param pageNo

* 页号

* @param rowsPerPage

* 每页显示条数

*/

public Page queryPage(Query query, int pageNo, int rowsPerPage);

/**

* 根据query查找记录

*

* @param query

* 查询条件

* @param firstResult

* 起始行

* @param maxResults

* 结束行

*/

public List query(Query query, int firstResult, int maxResults);

/**

* 根据query查找记录

*

* @param query

* 查询条件

*/

public List query(Query query);

/**

* 执行更新操作的jpql语句

*

* @param jpql

* 要执行的jpql语句

*/

public List query(String jpql);

public List queryAll(Class clazz);

public List query(String jpql, int firstResult, int maxResults);

/**

* 执行查询操作的sql语句

*

* @param sql

* 要执行的sql语句

*/

public List queryBySql(String sql);

public List queryBySql(String sql, int firstResult, int maxResults);

/**

* 查询记录

*

* @param clazz

* 要查询的实体类

* @param hqlCondition

* 查询条件

*/

public List query(Class clazz, String hqlCondition);

/**

* 执行更新操作的sql语句

*

* @param sql

* 要执行的sql语句

*/

public Integer updateSql(String sqhttp://l);

public Integer updateJpql(String jpql);

public Page queryPageByJpql(String hql, int pageNo, int rowsPerPage);

public void updateJpql(String jpql, List paramList);

}


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:百度取消移动搜索点赞按钮(百度点赞震动怎么关闭)
下一篇:#yyds干货盘点#H3C镜像端口配置学习(一)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~