package cn.gov.customs.data.repository.wxjy;//package cn.gov.customs.data.repository.riskh2000;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.hibernate.query.internal.NativeQueryImpl;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Transactional(value = "transactionManagerPrimary", propagation=Propagation.NOT_SUPPORTED)
@Repository
public class WxjyRepository {

    @PersistenceContext(unitName="entityManagerPrimary")
    EntityManager em;

    /**
     * 返回map结果集
     * @param sql
     * @param args
     * @return
     */
    public List<?> getQueryMapBySql(String sql, Object... args) {
        Query query = em.createNativeQuery(sql);

        query.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);

        if (args != null) {
            for (int i = 0; i < args.length; i++) {
                query.setParameter(i+1, args[i]);
            }
        }


        return query.getResultList();
    }

    /**
     * 返回指定的持久实例
     * @param sql
     * @param object
     * @return
     */
    public Object getObjectBySql(String sql, Object... object) {
        Query query = em.createNativeQuery(sql);
        if (object != null) {
            for (int i = 0; i < object.length; i++) {
                query.setParameter(i+1, object[i]);
            }
        }

        List list = query.getResultList();
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    /**
     * 用sql语句去查询，返回查询结果集合
     * @param sql
     * @param args
     * @return
     */
    public List<?> getQueryBySql(String sql, Object... args) {
        Query query = em.createNativeQuery(sql);
        if (args != null) {
            for (int i = 0; i < args.length; i++) {
                query.setParameter(i+1, args[i]);
            }
        }
        return query.getResultList();
    }

    @Transactional
    public int executeUpdate(String sql, Object... args) {
        Query query = em.createNativeQuery(sql);
        if (args != null) {
            for (int i = 0; i < args.length; i++) {
                query.setParameter(i+1, args[i]);
            }
        }
        int result = query.executeUpdate();
        return result;
    }

    /**
     * 返回指定的持久实例
     * @return
     */
    public String getGuidStringBySql() {
        Query query = em.createNativeQuery("select GUID()");
        List list = query.getResultList();
        if (list != null && list.size() > 0) {
            return (String)list.get(0);
        }
        return null;
    }
}
