javax.persistence.solrquery 查询语法solrquery 查询语法怎么得到查询出的结果

[代码全屏查看]-封装JPA(Hibernate)动态查询(CriteriaQuery)
[1].[代码] 封装为Query类
package com.platform.framework.dao.
import java.io.S
import java.util.ArrayL
import java.util.C
import java.util.D
import java.util.HashM
import java.util.I
import java.util.L
import java.util.M
import javax.persistence.EntityM
import javax.persistence.criteria.CriteriaB
import javax.persistence.criteria.CriteriaBuilder.In;
import javax.persistence.criteria.CriteriaQ
import javax.persistence.criteria.O
import javax.persistence.criteria.P
import javax.persistence.criteria.R
import org.apache.log4j.L
* Query基类&br&
* @describe:封装JPA CriteriaBuilder查询条件
* @author:yangjian1004
* @since:
@SuppressWarnings({ "unused", "unchecked", "rawtypes", "null", "hiding" })
public class Query implements Serializable {
private static final long serialVersionUID = 8929342L;
private static Logger log = Logger.getLogger(Query.class);
private EntityManager entityM
/** 要查询的模型对象 */
/** 查询条件列表 */
private List&Predicate&
private CriteriaQuery criteriaQ
private CriteriaBuilder criteriaB
/** 排序方式列表 */
private List&Order&
/** 关联模式 */
private Map&String, Query& subQ
private Map&String, Query& linkQ
/** 或条件 */
private List&Query& orQ
private String groupBy;
private Query() {
private Query(Class clazz, EntityManager entityManager) {
this.clazz =
this.entityManager = entityM
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))
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 ==
public void or(List&String& propertyName, Object value) {
if (isNullOrEmpty(value))
if ((propertyName == null) || (propertyName.size() == 0))
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&String& propertyName, String value) {
if (isNullOrEmpty(value) || (propertyName.size() == 0))
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)) {
this.predicates.add(criteriaBuilder.notEqual(from.get(propertyName), value));
* @param propertyName
* @param value
public void notIn(String propertyName, Collection value) {
if ((value == null) || (value.size() == 0)) {
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))
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)) {
this.predicates.add(criteriaBuilder.le(from.get(propertyName), value));
* @param propertyName
* @param value
public void lt(String propertyName, Number value) {
if (isNullOrEmpty(value)) {
this.predicates.add(criteriaBuilder.lt(from.get(propertyName), value));
* 大于等于
* @param propertyName
* @param value
public void ge(String propertyName, Number value) {
if (isNullOrEmpty(value)) {
this.predicates.add(criteriaBuilder.ge(from.get(propertyName), value));
* @param propertyName
* @param value
public void gt(String propertyName, Number value) {
if (isNullOrEmpty(value)) {
this.predicates.add(criteriaBuilder.gt(from.get(propertyName), value));
* @param propertyName
* @param value
public void in(String propertyName, Collection value) {
if ((value == null) || (value.size() == 0)) {
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 criteriaQ
private void addLinkCondition(Query query) {
Map subQuery = query.linkQ
if (subQuery == null)
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)
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 =
addOrder(propertyName, order);
public Class getModleClass() {
return this.
public String getProjection() {
return this.
public void setProjection(String projection) {
this.projection =
public Class getClazz() {
return this.
public List&Order& getOrders() {
public void setOrders(List&Order& orders) {
this.orders =
public EntityManager getEntityManager() {
return this.entityM
public void setEntityManager(EntityManager em) {
this.entityManager =
public Root getFrom() {
public List&Predicate& getPredicates() {
public void setPredicates(List&Predicate& predicates) {
this.predicates =
public CriteriaQuery getCriteriaQuery() {
return criteriaQ
public CriteriaBuilder getCriteriaBuilder() {
return criteriaB
public void setFetchModes(List&String& fetchField, List&String& fetchMode) {
public String getGroupBy() {
return groupBy;
public void setGroupBy(String groupBy) {
this.groupBy = groupBy;
[2].[代码] 查询片段
import mon.collect.L
import com.platform.framework.dao.jpa.EntityManagerFactoryP
import com.platform.framework.dao.jpa.IBaseD
import com.platform.framework.dao.jpa.Q
* @describe 查询实例
* @author 杨健/YangJian
* @since:
public class DemoServiceImpl extends EntityManagerFactoryProxy implements IDemoService {
private IBaseDao baseD
public void setBaseDao(IBaseDao baseDao) {
this.baseDao = baseD
* 城市列表
* @param pid
* @param search String
检索(拼音、名称)
* @param px
排序(3酒店数量4城市名称5拼音)
public List&ZnCity& getCity(String pid,String search,Integer px) {
String propertyName = "pinyin";
String order = "asc";
Query query = Query.forClass(ZnCity.class, getEntityManager());
if (!StringUtil.isBlank(pid) && "0".equals(pid)) {
query.setGroupBy("pid");
query.eq("pid", pid);
List&String& propertyNames =
Lists.newArrayList("CName","pinyin","suoxie");
query.orLike(propertyNames, search);
query.setOrder(propertyName, order);
List&ZnCity& znCitys = baseDao.query(query);
return znC
[3].[代码] IBaseDao接口
package com.platform.framework.dao.
import java.io.S
import java.util.L
import javax.persistence.EntityM
* IBaseDao基类&br&
* @describe:系统基础JPA Dao接口
* @author:yangjian1004
* @since:
@SuppressWarnings({ "rawtypes" })
public interface IBaseDao {
public EntityManager getEntityManager();
public &E& 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);
* 删除记录
* @param entity
要删除的记录
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 &E extends Serializable& List&E& query(Query query, int firstResult, int maxResults);
* 根据query查找记录
* @param query
public &E extends Serializable& List&E& query(Query query);
* 执行更新操作的jpql语句
* @param jpql
要执行的jpql语句
public &E extends Serializable& List&E& query(String jpql);
public &E extends Serializable& List&E& queryAll(Class clazz);
public &E extends Serializable& List&E& query(String jpql, int firstResult, int maxResults);
* 执行查询操作的sql语句
* @param sql
要执行的sql语句
public &E extends Serializable& List&E& queryBySql(String sql);
public &E extends Serializable& List&E& queryBySql(String sql, int firstResult, int maxResults);
* 查询记录
* @param clazz
要查询的实体类
* @param hqlCondition
public &E extends Serializable& List&E& query(Class clazz, String hqlCondition);
* 执行更新操作的sql语句
* @param sql
要执行的sql语句
public Integer updateSql(String sql);
public Integer updateJpql(String jpql);
public Page queryPageByJpql(String hql, int pageNo, int rowsPerPage);
public void updateJpql(String jpql, List paramList);
[4].[代码] BaseDaoImpl实现了IBaseDao接口
package com.platform.framework.dao.
import java.io.S
import java.util.L
import javax.persistence.EntityM
import javax.persistence.criteria.CriteriaQ
import javax.persistence.criteria.P
import javax.persistence.criteria.S
import javax.persistence.metamodel.EntityT
import org.apache.log4j.L
import mon.base.S
* IBaseDao接口实现了BaseDaoImpl类&br&
* @author:yangjian1004
* @since:
@SuppressWarnings({ "unchecked", "rawtypes" })
public class BaseDaoImpl&T& extends EntityManagerFactoryProxy implements IBaseDao {
private static Logger log = Logger.getLogger(BaseDaoImpl.class);
/** 每次批量操作数 */
private int batchSize = 50;
/** 设置每次操作数 */
public void setBatchSize(int batchSize) {
this.batchSize = batchS
public &E& 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);
} else if (entity instanceof Object[]) {
getEntityManager().persist(entity);
} catch (Exception e) {
e.printStackTrace();
* 批量增加
* @param list
要新增的数据
public void insertList(List list) {
EntityManager entityManager = getEntityManager();
if (list == null || list.size() == 0) {
int i = 0;
for (Object o : list) {
insert(o);
if (i % batchSize == 0) {
entityManager.flush();
log.debug(list.get(0).getClass() + "批量增加数据" + i + "条");
* 更新记录
* @param entity
要更新的记录
public void update(Object entity) {
if (entity instanceof List) {
this.updateList((List) entity);
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)
for (Object o : list) {
getEntityManager().remove(o);
getEntityManager().remove(entity);
public &E extends Serializable& List&E& 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 &E extends Serializable& List&E& queryBySql(String sql) {
return getEntityManager().createNativeQuery(sql).getResultList();
* 查询记录
* @param clazz
要查询的实体类
* @param hqlCondition
public &E extends Serializable& List&E& 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 &E extends Serializable& List&E& query(String jpql, int firstResult, int maxResults) {
List result = getEntityManager().createQuery(jpql).setFirstResult(firstResult).setMaxResults(maxResults)
.getResultList();
public &E extends Serializable& List&E& queryBySql(String sql, int firstResult, int maxResults) {
return getEntityManager().createNativeQuery(sql).setFirstResult(firstResult).setMaxResults(maxResults)
.getResultList();
public &E extends Serializable& List&E& 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 / rowsPerP
if (pageNo & totalPageCount && (count % rowsPerPage == 0)) {
pageNo = totalPageC
if (pageNo - totalPageCount & 2) {
pageNo = totalPageCount + 1;
int firstResult = (pageNo - 1) * rowsPerP
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=?"
,{[zx],[23]})
下午3:38:35
* @param jpql
占位符式的sql
* @param paramList
list里面装有[zx, 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);
* 分页查询
* @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 / rowsPerP
if (pageNo & totalPageCount && (count % rowsPerPage == 0)) {
pageNo = totalPageC
if (pageNo - totalPageCount & 2) {
pageNo = totalPageCount + 1;
int firstResult = (pageNo - 1) * rowsPerP
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 &E extends Serializable& List&E& query(Query query, int firstResult, int maxResults) {
List result = getEntityManager().createQuery(query.newCriteriaQuery()).setFirstResult(firstResult)
.setMaxResults(maxResults).getResultList();
* 根据query查找记录
* @param query
public &E extends Serializable& List&E& 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();
[5].[代码] Page分页和结果封装类
package com.platform.framework.dao.
import java.io.S
import java.util.ArrayL
import java.util.L
* Page基类&br&
* @describe:分页
* @author:yangjian1004
* @since:
public class Page&T& implements Serializable {
private static final long serialVersionUID = 746930L;
/** 总条数 */
/** 页码 */
private int pageNo;
/** 每页显示多少条 */
private int rowsPerP
/** 总页数 */
private int totalPageC
/** 起始条数 */
private int firstR
/** 结束条数 */
private int lastR
/** 查询结果集合形式的结果 */
private List&T&
/** 查询结果对象形式的结果 */
public I // 返回码
private boolean success =
public Page() {
public Page(List&T& list) {
this(list.size(), 1, list.size(), list);
public Page(int count, int pageNo, int rowsPerPage, List&T& result) {
if (rowsPerPage & 1) {
rowsPerPage = 1;
this.count =
this.pageNo = pageNo;
this.result =
this.rowsPerPage = rowsPerP
if (this.result == null)
this.result = new ArrayList&T&();
totalPageCount = count / rowsPerP
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) * rowsPerP
if (lastRow & count) {
/** 返回每页的条数 */
public int getCount() {
public List&T& getResult() {
public int getPageNo() {
return pageNo;
/** 返回每页的条数 */
public int getRowsPerPage() {
return rowsPerP
/** 返回总的页数 */
public int getTotalPageCount() {
return totalPageC
public void setPageNo(int pageNo) {
this.pageNo = pageNo;
public void setRowsPerPage(int rowsPerPage) {
this.rowsPerPage = rowsPerP
public int getFirstRow() {
return firstR
public int getLastRow() {
return lastR
public void setFirstRow(int firstRow) {
this.firstRow = firstR
public void setLastRow(int lastRow) {
this.lastRow = lastR
public void setCount(int count) {
this.count =
public void setTotalPageCount(int totalPageCount) {
this.totalPageCount = totalPageC
public void setResult(List&T& result) {
this.result =
public Object getObj() {
public void setObj(Object obj) {
this.obj =
public boolean isSuccess() {
public void setSuccess(boolean success) {
this.success =
public String getMessage() {
public void setMessage(String message) {
this.message =
* 计算起始条数
public static int calc(int pageNo, int rowsPerPage, int count) {
if (pageNo &= 0)
pageNo = 1;
if (rowsPerPage &= 0)
rowsPerPage = 10;
// 当把最后一页数据删除以后,页码会停留在最后一个上必须减一
int totalPageCount = count / rowsPerP
if (pageNo & totalPageCount && (count % rowsPerPage == 0)) {
pageNo = totalPageC
if (pageNo - totalPageCount & 2) {
pageNo = totalPageCount + 1;
int firstRow = (pageNo - 1) * rowsPerP
if (firstRow & 0) {
firstRow = 0;
return firstR
[6].[代码] EntityManager管理器,通过spring管理
package com.platform.framework.dao.
import java.util.C
import javax.persistence.EntityM
import javax.persistence.EntityManagerF
* EntityManager管理器
* @author:yangjian1004
* @since: 16:14:24 AM
public class EntityManagerFactoryProxy {
private static ThreadLocal&EntityManager& emThreadLocal = new ThreadLocal&EntityManager&();
private static EntityManagerF
public void setEmf(EntityManagerFactory emf) {
EntityManagerFactoryProxy.emf =
public static EntityManagerFactory getEmf() {
public EntityManager getEntityManager() {
return emThreadLocal.get();
public void setEntityManager(EntityManager em) {
emThreadLocal.set(em);
* 创建查询条件
* @param name
* @param values
public String createInCondition(String name, Collection&String& 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 hsqlC
[7].[代码] JPA事务管理
package com.platform.framework.dao.
import javax.persistence.EntityM
import javax.persistence.EntityManagerF
import javax.persistence.EntityT
import org.apache.log4j.L
import org.aspectj.lang.ProceedingJoinP
import org.aspectj.lang.S
* @describe JPA事务管理
* @author yangjian1004
* @since:
public class TransactionHandler {
private static final Logger log = Logger
.getLogger(TransactionHandler.class);
private String[]// 配置事务的传播特性方法
private EntityManagerFactory entityManagerF// JPA工厂
public Object exec(ProceedingJoinPoint point) throws Throwable {
Signature signature = point.getSignature();
log.debug(point.getTarget().getClass().getName() + "."
+ signature.getName() + "()");
Boolean isTransaction =
for (String method : txmethod) {
if (signature.getName().startsWith(method)) {// 以method开头的方法打开事务
isTransaction =
// JPA-&Hibernate
if (point.getTarget() instanceof EntityManagerFactoryProxy) {
// 获得被代理对象
EntityManagerFactoryProxy emfp = (EntityManagerFactoryProxy) point
.getTarget();
EntityManager em = emfp.getEntityManager();
if (em != null) {// 如果对象已经有em了就不管
return point.proceed();
em = entityManagerFactory.createEntityManager();
log.debug("JPA-&Hibernate open connection...");
if (isTransaction) {
EntityTransaction t =
// 打开连接并开启事务
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();
} catch (Exception e) {
if (t != null) {
log.debug("JPA-&Hibernate error...,rollback..."
+ e.getMessage());
t.rollback();
e.printStackTrace();
} finally {
if (em != null && em.isOpen()) {// 关闭连接
em.close();
log.debug("JPA-&Hibernate close connection...");
emfp.setEntityManager(null);
emfp.setEntityManager(em);
return point.proceed();
} catch (Exception e) {
log.debug("JPA-&Hibernate error..." + e.getMessage());
e.printStackTrace();
} finally {
if (em != null && em.isOpen()) {// 关闭连接
em.close();
log.debug("JPA-&Hibernate close connection...");
emfp.setEntityManager(null);
return point.proceed();
public String[] getTxmethod() {
public void setTxmethod(String[] txmethod) {
this.txmethod =
public void setEntityManagerFactory(
EntityManagerFactory entityManagerFactory) {
this.entityManagerFactory = entityManagerF
[8].[代码] spring hibernate jpa 配置文件
&?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:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.1.xsd"&
&!-- JPA Entity Manager Factory --&
&bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:packagesToScan="com.**.model" p:dataSource-ref="dataSource"
p:jpaVendorAdapter-ref="hibernateVendor" p:jpaPropertyMap-ref="jpaPropertyMap"/&
&util:map id="jpaPropertyMap"&
&entry key="hibernate.hbm2ddl.auto" value="update" /&&!-- create,update,none --&
&entry key="hibernate.format_sql" value="false" /&
&entry key="hibernate.show_sql" value="false" /&
&entry key="hibernate.current_session_context_class" value="org.hibernate.context.internal.ThreadLocalSessionContext"/&
&entry key="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" /&
&!-- To enable Hibernate's second level cache and query cache settings --&
&entry key="hibernate.max_fetch_depth" value="4" /&
&entry key="hibernate.cache.use_second_level_cache" value="true" /&
&entry key="hibernate.cache.use_query_cache" value="true" /&
&!-- &entry key="hibernate.cache.region.factory_class" value="org.hibernate.cache.ehcache.EhCacheRegionFactory" /& --&
&entry key="hibernate.cache.region.factory_class" value="org.hibernate.cache.SingletonEhCacheRegionFactory" /&
&/util:map&
&bean id="hibernateVendor"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
p:database="MYSQL" p:showSql="true" p:generateDdl="true"
p:databasePlatform="org.hibernate.dialect.MySQLDialect" /&
&bean id="transactionHandler" class="com.platform.framework.dao.jpa.TransactionHandler" &
&property name="txmethod"&
&value&insert&/value&
&value&update&/value&
&value&delete&/value&
&/property&
&property name="entityManagerFactory" ref="entityManagerFactory"/&
&aop:config&
&aop:aspect id="tran" ref="transactionHandler"&
&aop:pointcut
id="tranMethod"
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.*(..))"/&
&aop:around method="exec"
pointcut-ref="tranMethod" /&
&/aop:aspect&
&/aop:config&
&bean id="baseDao" class="com.platform.framework.dao.jpa.BaseDaoImpl"&
&property name="emf" ref="entityManagerFactory"/&
[9].[代码] ZnCity实体类
import java.io.S
import javax.persistence.C
import javax.persistence.E
import javax.persistence.Id;
import javax.persistence.T
@Table(name = "zn_city")
public class ZnCity implements Serializable{
private static final long serialVersionUID = 6228293L;
private S//": "0101",
private S//": "0100",
private String pN//": "北京",
private String cN//": "北京",
private S//": 53,
private S//": "B",
private S//": "BJ",
private S//": "BeiJing",
private Integer hotelN//": 2532,
private Float baidu_//": 39.929986,
private Float baidu_//": 116.395645
public String getCid() {
public void setCid(String cid) {
this.cid =
@Column(length=60)
public String getPid() {
public void setPid(String pid) {
this.pid =
@Column(length=60)
public String getPName() {
public void setPName(String pName) {
this.pName = pN
@Column(length=60)
public String getCName() {
public void setCName(String cName) {
@Column(length=60)
public String getAreaid() {
public void setAreaid(String areaid) {
this.areaid =
@Column(length=60)
public String getAbcd() {
public void setAbcd(String abcd) {
this.abcd =
@Column(length=64)
public String getSuoxie() {
public void setSuoxie(String suoxie) {
this.suoxie =
@Column(length=100)
public String getPinyin() {
public void setPinyin(String pinyin) {
this.pinyin =
public Integer getHotelNum() {
return hotelN
public void setHotelNum(Integer hotelNum) {
this.hotelNum = hotelN
public Float getBaidu_lat() {
return baidu_
public void setBaidu_lat(Float baidu_lat) {
this.baidu_lat = baidu_
public Float getBaidu_lng() {
return baidu_
public void setBaidu_lng(Float baidu_lng) {
this.baidu_lng = baidu_
[10].[代码] 数据量连接池app-datesource.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"&
&bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"&
&!-- 基本属性 url、user、password --&
&property name="driverClassName" value="com.mysql.jdbc.Driver" /&
&property name="url" value="jdbc:mysql://localhost:3306/demo_jpa?useUnicode=true&characterEncoding=UTF8" /&
&property name="username" value="root" /&
&property name="password" value="root" /&
&!-- 配置初始化大小、最小、最大 --&
&property name="initialSize" value="10" /&
&property name="minIdle" value="5" /&
&property name="maxActive" value="300" /&
&!-- 配置获取连接等待超时的时间 --&
&property name="maxWait" value="60000" /&
&!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --&
&property name="timeBetweenEvictionRunsMillis" value="60000" /&
&!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --&
&property name="minEvictableIdleTimeMillis" value="300000" /&
&property name="validationQuery" value="SELECT 'x'" /&
&property name="testWhileIdle" value="true" /&
&property name="testOnBorrow" value="false" /&
&property name="testOnReturn" value="false" /&
&!-- 打开PSCache,并且指定每个连接上PSCache的大小 --&
&property name="poolPreparedStatements" value="true" /&
&property name="maxPoolPreparedStatementPerConnectionSize" value="20" /&
&!-- 配置监控统计拦截的filters --&
&property name="filters" value="stat" /&
[11].[代码] 数据库脚本zn_city.sql
SQLyog v10.2
MySQL - 5.5.32 : Database - demo_jpa
*********************************************************************
/*!40101 SET NAMES utf8 */;
/*!40101 SET SQL_MODE=''*/;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`demo_jpa` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `demo_jpa`;
/*Table structure for table `zn_city` */
DROP TABLE IF EXISTS `zn_city`;
CREATE TABLE `zn_city` (
`cid` varchar(60) NOT NULL,
`abcd` varchar(60) DEFAULT NULL,
`areaid` varchar(60) DEFAULT NULL,
`baidu_lat` float DEFAULT NULL,
`baidu_lng` float DEFAULT NULL,
`cName` varchar(60) DEFAULT NULL,
`hotelNum` int(11) DEFAULT NULL,
`pName` varchar(60) DEFAULT NULL,
`pid` varchar(60) DEFAULT NULL,
`pinyin` varchar(100) DEFAULT NULL,
`suoxie` varchar(64) DEFAULT NULL,
PRIMARY KEY (`cid`),
KEY `cName` (`cName`,`pid`,`pinyin`,`suoxie`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*Data for the table `zn_city` */
into `zn_city`(`cid`,`abcd`,`areaid`,`baidu_lat`,`baidu_lng`,`cName`,`hotelNum`,`pName`,`pid`,`pinyin`,`suoxie`) values ('0101','B','53',39.93,116.396,'北京',4013,'北京','0100','BeiJing','BJ'),('0201','S','321',31.,'上海',3928,'上海','0200','ShangHai','SH'),('0205','F','7,121.484,'奉贤博物馆',0,'上海','0200','FengXianBoWuGuan','FXBWG'),('0301','T','343',39.,'天津',1035,'天津','0300','TianJin','TJ'),('0401','C','394',29.,'重庆',1882,'重庆','0400','ChongQing','CQ'),('0402','W','6,108.415,'万州(重庆)',0,'重庆','0400','WanZhou','WZ');
[12].[文件]
zn_city.sql&~&2KB&&&&(28)
SQLyog v10.2
MySQL - 5.5.32 : Database - demo_jpa
*********************************************************************
/*!40101 SET NAMES utf8 */;
/*!40101 SET SQL_MODE=''*/;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`demo_jpa` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `demo_jpa`;
/*Table structure for table `zn_city` */
DROP TABLE IF EXISTS `zn_city`;
CREATE TABLE `zn_city` (
`cid` varchar(60) NOT NULL,
`abcd` varchar(60) DEFAULT NULL,
`areaid` varchar(60) DEFAULT NULL,
`baidu_lat` float DEFAULT NULL,
`baidu_lng` float DEFAULT NULL,
`cName` varchar(60) DEFAULT NULL,
`hotelNum` int(11) DEFAULT NULL,
`pName` varchar(60) DEFAULT NULL,
`pid` varchar(60) DEFAULT NULL,
`pinyin` varchar(100) DEFAULT NULL,
`suoxie` varchar(64) DEFAULT NULL,
PRIMARY KEY (`cid`),
KEY `cName` (`cName`,`pid`,`pinyin`,`suoxie`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*Data for the table `zn_city` */
into `zn_city`(`cid`,`abcd`,`areaid`,`baidu_lat`,`baidu_lng`,`cName`,`hotelNum`,`pName`,`pid`,`pinyin`,`suoxie`) values ('0101','B','53',39.93,116.396,'北京',4013,'北京','0100','BeiJing','BJ'),('0201','S','321',31.,'上海',3928,'上海','0200','ShangHai','SH'),('0205','F','7,121.484,'奉贤博物馆',0,'上海','0200','FengXianBoWuGuan','FXBWG'),('0301','T','343',39.,'天津',1035,'天津','0300','TianJin','TJ'),('0401','C','394',29.,'重庆',1882,'重庆','0400','ChongQing','CQ'),('0402','W','6,108.415,'万州(重庆)',0,'重庆','0400','WanZhou','WZ');

我要回帖

更多关于 javax.persistence.id 的文章

 

随机推荐