1. Create EntityManager with annotations:
/*unitName is used to select a specific PersistenceContext and the primary data source is selected by default, which passes through the.persistenceUnit("secondaryPersistenceUnit") when creating the bean s of the data source
To create it by */on the object of EntityManagerFactoryBuilder
@PersistenceContext(unitName
= "secondaryPersistenceUnit")
EntityManager entityManager;
2. Create SQLQuery:
-
Session session = entityManager.unwrap(org.hibernate.Session.class);
-
SQLQuery query = session.createSQLQuery(sql);
-
List list=query.list();
3. Notes:
Database operation requires transaction annotation @Transactional
4. An encapsulated tool class:
-
package com.dean.app.service.system;
-
-
import java.beans.Introspector;
-
import java.beans.PropertyDescriptor;
-
import java.lang.reflect.Method;
-
import java.math.BigInteger;
-
import java.util.ArrayList;
-
import java.util.List;
-
import java.util.Map;
-
-
import javax.persistence.EntityManager;
-
import javax.persistence.PersistenceContext;
-
import javax.persistence.Query;
-
import javax.transaction.Transactional;
-
-
import org.apache.commons.beanutils.ConvertUtils;
-
import org.hibernate.SQLQuery;
-
import org.hibernate.Session;
-
import org.hibernate.transform.Transformers;
-
import org.springframework.stereotype.Repository;
-
import org.springframework.util.CollectionUtils;
-
-
@Transactional
-
@Repository
-
public class CommonDao {
-
-
@PersistenceContext
-
EntityManager entityManager;
-
-
-
-
-
-
-
-
-
@SuppressWarnings("unchecked")
-
public List<?> queryListEntity(String sql,Map<String, Object> params, Class<?> clazz){
-
Session session = entityManager.unwrap(org.hibernate.Session.class);
-
SQLQuery query = session.createSQLQuery(sql);
-
if (params != null) {
-
for (String key : params.keySet()) {
-
query.setParameter(key, params.get(key));
-
}
-
}
-
query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
-
List<Map<String, Object>> result = query.list();
-
if (clazz != null) {
-
List<Object> entityList = convert(clazz, result);
-
return entityList;
-
}
-
return result;
-
}
-
-
private List<Object> convert(Class<?> clazz, List<Map<String, Object>> list) {
-
List<Object> result;
-
if (CollectionUtils.isEmpty(list)) {
-
return null;
-
}
-
result = new ArrayList<Object>();
-
try {
-
PropertyDescriptor[] props = Introspector.getBeanInfo(clazz).getPropertyDescriptors();
-
for (Map<String, Object> map : list) {
-
Object obj = clazz.newInstance();
-
for (String key:map.keySet()) {
-
String attrName = key.toLowerCase();
-
for (PropertyDescriptor prop : props) {
-
attrName = removeUnderLine(attrName);
-
if (!attrName.equals(prop.getName())) {
-
continue;
-
}
-
Method method = prop.getWriteMethod();
-
Object value = map.get(key);
-
if (value != null) {
-
value = ConvertUtils.convert(value,prop.getPropertyType());
-
}
-
method.invoke(obj,value);
-
}
-
}
-
result.add(obj);
-
}
-
} catch (Exception e) {
-
throw new RuntimeException("Data conversion error");
-
}
-
return result;
-
}
-
-
private String removeUnderLine(String attrName) {
-
-
if(attrName.contains("_")) {
-
String[] names = attrName.split("_");
-
String firstPart = names[0];
-
String otherPart = "";
-
for (int i = 1; i < names.length; i++) {
-
String word = names[i].replaceFirst(names[i].substring(0, 1), names[i].substring(0, 1).toUpperCase());
-
otherPart += word;
-
}
-
attrName = firstPart + otherPart;
-
}
-
return attrName;
-
}
-
-
-
-
-
-
-
-
public Integer getCountBy(String sql,Map<String, Object> params){
-
Query query = entityManager.createNativeQuery(sql);
-
if (params != null) {
-
for (String key : params.keySet()) {
-
query.setParameter(key, params.get(key));
-
}
-
}
-
BigInteger bigInteger = (BigInteger) query.getSingleResult();
-
return bigInteger.intValue();
-
}
-
-
-
-
-
-
-
-
public Integer deleteOrUpDate(String sql,Map<String, Object> params){
-
Query query = entityManager.createNativeQuery(sql);
-
if (params != null) {
-
for (String key : params.keySet()) {
-
query.setParameter(key, params.get(key));
-
}
-
}
-
return query.executeUpdate();
-
}
-
}
1. The integer returned by the getCountBy() method in the code above needs to be transformed because the database returns BigInteger
2. There is also data where the underlined field does not correspond to the entity, so the underline needs to be removed and the first letter of the string after the underline needs to be converted to uppercase, such as login_name for the field in the database and loginName for the entity object defined by the field itself, where the conversion is only to be universal.When not converting, you only need to write SQL with an alias and an entity.
3. If you don't need to convert to a specific entity, you can either use the List <Map <String, Object> collection directly or use query.setResultTransformer(Transformers.toBean(clazz)) directly to convert to the specified entity, but if some fields in the database are bigint (I'm using it) MySQL Database) Then the corresponding attributes of the entity you define need to be of type BigInterger, otherwise type conversion errors will be reported.Other databases have not been tested, so just change them.
top
2