package cn.gov.customs.data.repository.h2018app;

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;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;

@Transactional(value = "transactionManagerH2018app", propagation=Propagation.NOT_SUPPORTED, readOnly=true)
@Repository
public class H2018appRepository {


	@PersistenceContext(unitName = "entityManagerH2018app")
	 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
	 * @return
	 */
	public Object getObjectBySql(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]);
				}
			}
	        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();
	}

}
