package com.jiayue.ipfcst.common.data.repository;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * EntityManager仓储，执行sql语句。
 *
 * @author bizy
 * @version 3.0
 */
@Repository
@Slf4j
public class EntityManagerRepository {
	@PersistenceContext
	private EntityManager em;

	@Modifying
	@Transactional(rollbackFor = Exception.class)
	public int executeSql(String sql) {
		int r = 0;
		if (!sql.isEmpty()) {
			try {
				Query query = em.createNativeQuery(sql);
				r = query.executeUpdate();
				log.debug("sql语句：" + sql + "，执行" + (r == 1 ? "成功" : "失败"));
			} catch (Exception e) {
				log.error("系统错误：" + e.getMessage(), e);
			}
		}
		return r;
	}

	@Modifying
	@Transactional(rollbackFor = Exception.class)
	public boolean executeSql(List<String> sqlList) {
		boolean flag = false;
		for (String sql : sqlList) {
			if (!sql.isEmpty()) {
				try {
					Query query = em.createNativeQuery(sql);
					int r = query.executeUpdate();
					log.debug("sql语句：" + sql + "，执行" + (r == 1 ? "成功" : "失败"));
					flag = true;
				} catch (Exception e) {
					flag = false;
					log.error("系统错误：" + e.getMessage(), e);
				}
			}
		}
		return flag;
	}
}
