xyz.erupt.jpa.dao.EruptDao Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of erupt-jpa Show documentation
Show all versions of erupt-jpa Show documentation
EruptProcess database impl
package xyz.erupt.jpa.dao;
import org.apache.commons.lang3.StringUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Component;
import xyz.erupt.annotation.config.Comment;
import xyz.erupt.jpa.service.EntityManagerService;
import javax.annotation.Resource;
import javax.persistence.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
* @author YuePeng
* date 2019-12-23
*/
@Component
public class EruptDao {
@PersistenceContext
private EntityManager entityManager;
@Resource
private EntityManagerService entityManagerService;
@Resource
private JdbcTemplate jdbcTemplate;
@Resource
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
private static final String SELECT = "select ";
private static final String FROM = " from ";
private static final String NEW_MAP = "new map(";
private static final String AS = " as ";
private static final String EQU = " = ";
private static final String WHERE = " where ";
public T findById(Class clazz, Object id) {
entityManager.clear();
return entityManager.find(clazz, id);
}
//修改
public T merge(T t) {
return entityManager.merge(t);
}
public T mergeAndFlush(T t) {
try {
return this.merge(t);
} finally {
this.flush();
}
}
public void flush() {
entityManager.flush();
}
//删除
public void delete(Object obj) {
entityManager.remove(obj);
}
//新增
public void persist(Object obj) {
entityManager.persist(obj);
}
public void persistAndFlush(Object obj) {
this.persist(obj);
this.flush();
}
public EntityManager getEntityManager() {
return entityManager;
}
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public NamedParameterJdbcTemplate getNamedParameterJdbcTemplate() {
return namedParameterJdbcTemplate;
}
@Comment("根据数据源名称获取 EntityManager 注意:必须手动执行 entityManager.close() 方法")
public EntityManager getEntityManager(String name) {
return entityManagerService.findEntityManager(name);
}
//不存在则新增
public T persistIfNotExist(Class eruptClass, T obj, String field, String val) throws NonUniqueResultException {
T t = (T) queryEntity(eruptClass, field + EQU + " :val", new HashMap(1) {{
this.put("val", val);
}});
if (null == t) {
entityManager.persist(obj);
entityManager.flush();
return obj;
}
return t;
}
//以下方法调用时需考虑sql注入问题,切勿随意传递expr参数值!!!
public List
© 2015 - 2024 Weber Informatics LLC | Privacy Policy