Spring Data / Hibernate 動態查詢

BaseQuery.javajava

說明:Sql 拼接spring

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import java.util.List;
import java.util.Map;

/**
 * Created by pw on 2016/12/22.
 */
public class BaseQuery{

    @Autowired
    private EntityManagerFactory entityManagerFactory;

    @Autowired
    private EntityManager entityManager;

    /**
     * 建立 Query 並 設置查詢條件(不帶排序)
     * @param className
     * @param values
     * @param <T>
     * @return
     */
    protected  <T> Query select(Class<T> className, Map<String, Object> values){
        return selectStatement(className,values);
    }


    public <T> T querySingleResult(Class<T> clazz, Map<String, Object> varables){
        return (T)selectStatement(clazz, varables).getSingleResult();
    }

    /**
     * 單表多條記錄查詢
     * @param className 要查詢的對象
     * @param values 封裝查詢條件的map
     * @return 返回查詢結果的List集合
     */
    public <T> List<T> queryResultList(Class<T> className, Map<String,Object> values){
        return  selectStatement(className, values).getResultList();
    }


    /**
     * 拼接SQL查詢字符串,獲得Query並賦值查詢條件
     *
     * @param className
     * @param values
     * @return Query
     */
    private <T> Query selectStatement(Class<T> className, Map<String, Object> values) {
        StringBuilder stringBuilder = new StringBuilder();
        // TODO 待優化
        SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);
        /*
         * 經過className獲得該實體類的字符串形式,
         */
        stringBuilder.append("from " + sessionFactory.getClassMetadata(className).getEntityName());
        stringBuilder.append(" where 1=1 ");
        /*
         * 動態的拼接sql語句,若是一個屬性的值爲"", 則不往條件中添加.
         */
        for (Map.Entry<String, Object> entry : values.entrySet()) {
            if (!entry.getValue().equals("")) { // TODO 待優化
                stringBuilder.append(" and " + entry.getKey() + "=:" + entry.getKey());
            }
        }
        
        Query entityManagerQuery = entityManager.createQuery(stringBuilder.toString());
        for (Map.Entry<String, Object> entry : values.entrySet()) {
            if (null != entry.getValue() && !"".equals(entry.getValue())) {
                entityManagerQuery.setParameter(entry.getKey(), entry.getValue());
            }
        }
        return entityManagerQuery;
    }

}

BeanUtil.javasql

做用JavaBean ->Map 而且駝峯命名 改成 下劃線命名json

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by pw on 2016/12/22.
 */
public class BeanUtil {

    private static final Logger logger = LoggerFactory.getLogger(BeanUtil.class);

    public static Map<String, Object> beanToMap(Object obj) {
        if(obj == null) return null;
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor property : propertyDescriptors) {
                String key = property.getName();
                if (!key.equals("class")) {
                    Object value = property.getReadMethod().invoke(obj);
                    if(null !=value) map.put(key.replaceAll("[A-Z]", "_$0").toLowerCase(), value);
                }
            }
        } catch (Exception e) {
            logger.info("beanToMap-->>",e);
        }
        return map;
    }

}

VwWarehouseInventoryDetailQuery.javaapi

實際應用案例session

import com.avp.mem.entity.api.entity.VwWarehouseInventoryDetail;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * Created by pw on 2016/12/22.
 */
@Component
public class VwWarehouseInventoryDetailQuery extends BaseQuery{


    public VwWarehouseInventoryDetail querySingleResult(Map<String, Object> varables){
        return super.querySingleResult(VwWarehouseInventoryDetail.class, varables);
    }

    public List<VwWarehouseInventoryDetail> queryResultList( Map<String, Object> values) {
        return super.queryResultList(VwWarehouseInventoryDetail.class, values);
    }

}

 

SpringBoot + SpringData Junit 測試app

import com.alibaba.fastjson.JSON;
import com.avp.mems.stock.StockApplication;
import com.avp.mems.stock.dao.query.VwWarehouseInventoryDetailQuery;
import com.avp.mems.stock.parameter.WarehouseInventoryDetailParameter;
import com.avp.mems.stock.repositories.ObjWarehouseRepository;
import com.avp.mems.stock.utils.BeanUtil;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by pw on 2016/12/22.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = StockApplication.class)
public class VwWarehouseMaterialTest {


    @Autowired
    private VwWarehouseInventoryDetailQuery warehouseInventoryDetailQuery;

    @Autowired
    private ObjWarehouseRepository warehouseRepository;

    @Test
    public void test1(){
        Map<String,Object> map = new HashMap();
        map.put("id",10007);
        System.out.println(JSON.toJSON(warehouseInventoryDetailQuery.querySingleResult(map)));

        System.out.println("--------------------------");

        map = new HashMap<>();
        map.put("inventory_detail_type_id",1);
        map.put("inventory_detail_data_type_id",0);
        System.out.println(JSON.toJSON(warehouseInventoryDetailQuery.queryResultList(map)));
    }

//    @Test
//    public void test2(){
//        System.out.println(JSON.toJSON(warehouseRepository.findAll()));
//    }

    @Test
    public void test3(){
        //參數對象
        WarehouseInventoryDetailParameter parameter = new WarehouseInventoryDetailParameter();
        parameter.setInventoryDetailTypeId(2);
        System.out.println(JSON.toJSON(warehouseInventoryDetailQuery.queryResultList(BeanUtil.beanToMap(parameter))));
    }

}
相關文章
相關標籤/搜索