package simple.page.service.database; import java.util.List; import java.util.Map; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import org.hibernate.SQLQuery; import org.hibernate.transform.Transformers; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; /** * 執行原生SQL Service * @author 周超 2014-6-16 */ @Component public class SqlService { @PersistenceContext EntityManager em; public List<Map<String,Object>> queryBySql(String sql){ Query query = em.createNativeQuery(sql); @SuppressWarnings("unchecked") List<Map<String,Object>> list = query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list(); return list; } @Transactional public void excuteSql(String sql){ Query query = em.createNativeQuery(sql); query.executeUpdate(); } }
em.createNativeQuery(sql)返回的是javax.persistence.Queryjava
能夠用unwrap方法轉換成SQLQuery(這個是hibernate的)spring
以後再用setResultTransformer方法將結果轉換成Map類型。sql
這樣能夠便於抽成通用方法。網上的大多數都是沒有列名的,返回數組經過下標取值。數組