All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.dromara.trans.extend.JPA2SimpleTransDiver Maven / Gradle / Ivy

There is a newer version: 2.3.1
Show newest version
package org.dromara.trans.extend;

import org.dromara.core.trans.util.ReflectUtils;
import org.dromara.core.trans.vo.VO;
import org.dromara.trans.service.impl.SimpleTransService;
import org.springframework.util.StringUtils;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.TypedQuery;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * JPA2简单翻译驱动
 */
public class JPA2SimpleTransDiver implements SimpleTransService.SimpleTransDiver {
    private EntityManager em;

    public JPA2SimpleTransDiver(EntityManager em) {
        this.em = em;
    }

    @Override
    public List findByIds(List ids, Class targetClass,String uniqueField) {
        if(!StringUtils.isEmpty(uniqueField)){
            throw new RuntimeException("JPA不支持唯一索引来代替ID查询");
        }
        if (ids == null || ids.isEmpty()) {
            return new ArrayList();
        }
        TypedQuery query = em.createQuery(getSelectSql(targetClass)
                + " WHERE tbl." + getPkeyFieldName(targetClass) + " IN :ids", targetClass);
        query.setParameter("ids", ids);
        return query.getResultList();
    }

    @Override
    public VO findById(Serializable id, Class targetClass,String uniqueField) {
        if(!StringUtils.isEmpty(uniqueField)){
            throw new RuntimeException("JPA不支持唯一索引来代替ID查询");
        }
        TypedQuery query = em.createQuery(getSelectSql(targetClass)
                + " WHERE tbl." + getPkeyFieldName(targetClass) + " = :id", targetClass);
        query.setParameter("id", id);
        try{
            return (VO) query.getSingleResult();
        }catch (NoResultException e) {
            return null;
        }
    }

    private String getSelectSql(Class targetClass) {
        return "FROM " + targetClass.getSimpleName() + " AS tbl ";
    }

    private String getPkeyFieldName(Class targetClass) {
        List fieldList = ReflectUtils.getAnnotationField(targetClass, javax.persistence.Id.class);
        if (fieldList == null || fieldList.isEmpty()) {
            throw new RuntimeException(targetClass.getName() + "没有@Id标记");
        }
        return fieldList.get(0).getName();
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy