package com.kucun.Service;
import java.io.Serializable;
import java.lang.reflect.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;
import com.kucun.data.entity.Bancai;
import com.kucun.data.entity.Dingdan_chanpin;
import com.kucun.data.entity.Dingdan_chanpin_zujian;
import com.kucun.data.entity.EntityBasis;
import com.kucun.data.entity.Information;
import com.kucun.data.entity.Kucun;
import com.kucun.dataDo.BancaiRepository;
import com.kucun.dataDo.CaizhiRepository;
import com.kucun.dataDo.ChanpinRepository;
import com.kucun.dataDo.ChanpinZujianRepository;
import com.kucun.dataDo.DingdanChanpinRepository;
import com.kucun.dataDo.DingdanChanpinZujianRepository;
import com.kucun.dataDo.DingdanRepository;
import com.kucun.dataDo.KucunRepository;
import com.kucun.dataDo.MupiRepository;
import com.kucun.dataDo.UserRepository;
import com.kucun.dataDo.ZujianRepository;
@Service
public class AppService {
// 注入所有需要的Repository
@Autowired private CaizhiRepository caizhiRepository;
@Autowired private BancaiRepository bancaiRepository;
@Autowired private ChanpinRepository chanpinRepository;
@Autowired private DingdanRepository dingdanRepository;
@Autowired private MupiRepository mupiRepository;
@Autowired private ZujianRepository zujianRepository;
@Autowired private KucunRepository kucunRepository;
@Autowired private UserRepository userRepository;
@Autowired private ChanpinZujianRepository chanpinZujianRepository;
@Autowired private DingdanChanpinZujianRepository dingdanChanpinZujianRepository;
@Autowired private DingdanChanpinRepository dingdanChanpinRepository;
@Autowired private DynamicRepositoryService repositoryService;
@Autowired private EntityDependencyService dependencyService;
public Information getAllDataWithChildIdse() {
Map<String, Object> response = new HashMap<>();
for (String key : repositoryService.getRepositoryNameMap().keySet()) {
response.put(key+"s", (repositoryService.getJpaRepository(key).findAll()));
}
return Information.NewSuccess(response);
}
public Information getAllDataWithChildIdse(String e) {
JpaRepository<?, ?> jp = repositoryService.getJpaRepository(e);
System.out.println(jp);
return Information.NewSuccess(jp.findAll());
}
public Information getAddEntity(Object e) {
Class<?> entityClass = e.getClass();
try {
// 处理关联字段
handleAssociations(e);
@SuppressWarnings("unchecked")
JpaRepository<Object, Serializable> jp =
(JpaRepository<Object, Serializable>) repositoryService.getJpaRepository(entityClass);
Object savedEntity = jp.save(e);
if(savedEntity!=null) {
if(savedEntity instanceof Bancai) {
initializeKucunForBancai((Bancai)savedEntity);
}
}
return Information.NewSuccess(savedEntity);
} catch (Exception ex) {
return Information.Newfail(500, "创建失败: " + ex.getMessage(), null);
}
}
// 单独封装库存初始化方法
private void initializeKucunForBancai(Bancai bancai) throws Exception {
Kucun kucun = new Kucun(null, bancai, 0); // 初始库存为0
try {
bancai.setKucun(kucunRepository.save(kucun));
} catch (Exception e) {
// TODO: handle exception
throw new Exception("initializeKucunForBancai"+e);
}
}
// 处理关联对象(转换为托管实体)
private void handleAssociations(Object entity)
throws Exception {
Class<?> clazz = entity.getClass();
for (Field field : clazz.getDeclaredFields()) {
field.setAccessible(true);
Object value = field.get(entity);
if (value == null) continue;
// 处理单个关联实体
if (isEntityBasisField(field)) {
EntityBasis associatedEntity = (EntityBasis) value;
JpaRepository<Object, Serializable> repo =
(JpaRepository<Object, Serializable>) repositoryService.getJpaRepository(associatedEntity.getClass());
// 获取托管状态的关联实体
Object managedEntity = repo.findById(associatedEntity.getId())
.orElseThrow(() -> new RuntimeException("关联实体不存在"));
field.set(entity, managedEntity);
}
// 处理集合关联
else if (isCollectionField(field)) {
Collection<?> collection = (Collection<?>) value;
List<Object> managedEntities = new ArrayList<>();
for (Object item : collection) {
if (item instanceof EntityBasis) {
EntityBasis eb = (EntityBasis) item;
JpaRepository<Object, Serializable> repo =
(JpaRepository<Object, Serializable>) repositoryService.getJpaRepository(eb.getClass());
Object managedEntity = repo.findById(eb.getId())
.orElseThrow(() -> new RuntimeException("关联实体不存在"));
managedEntities.add(managedEntity);
}
}
// 更新集合为托管实体
if (!managedEntities.isEmpty()) {
field.set(entity, managedEntities);
}
}
}
}
/**
* 更新
* @param e 实体待id
* @return
*/
/**
* 更新实体
* @param e 包含ID的实体
* @return 操作结果
*/
public Information getupdateEntity(Object e) {
if(e == null) {
return Information.Newfail(403, "参数为空", null);
}
Class<?> entityClass = e.getClass();
try {
Field idField = entityClass.getDeclaredField("id");
idField.setAccessible(true);
Object idValue = idField.get(e);
// 修正:应检查id是否为空,而不是不为空
if(idValue == null) {
return Information.Newfail(403, "Id为空", null);
}
// 获取Repository
@SuppressWarnings("unchecked")
JpaRepository<Object, Serializable> jp =
(JpaRepository<Object, Serializable>) repositoryService.getJpaRepository(entityClass);
// 从数据库加载现有实体(托管状态)
Object existingEntity = jp.findById((Serializable) idValue)
.orElseThrow(() -> new RuntimeException("实体不存在"));
// 复制属性(排除关联字段)
copyNonNullProperties(e, existingEntity);
// 保存托管状态的实体
Object updatedEntity = jp.save(existingEntity);
return Information.NewSuccess(updatedEntity);
} catch (Exception ex) {
return Information.Newfail(500, "更新失败: " + ex.getMessage(), null);
}
}
/**
* 删除
* @param entity
* @return
*/
public Information getdeleteEntity(EntityBasis entity) {
Map<String, Object> response = new HashMap<>();
JpaRepository<Object, Integer> jp= (JpaRepository<Object, Integer>) repositoryService.getJpaRepository(entity.getClass().getSimpleName().toLowerCase());
if(!jp.existsById(entity.getId())) {
return Information.NewFail("没有该数据");
}
Object d=jp.findById(entity.getId()).orElse(null);
for (Class<?> nt : repositoryService.getRepositoryMap().keySet()) {
for (Field ent : nt.getDeclaredFields()) {
if(ent.getClass().equals(entity.getClass())) {
Object o=null;
try {
o = nt.newInstance();
ent.set(o, d);
} catch (InstantiationException | IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(o);
if(getSELECTEntity(o).getData()!=null) {
return Information.NewFail("已在其他地方使用了,无法删除");
}
}
}
}
try {
jp.deleteById(((EntityBasis)entity).getId());
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.getLocalizedMessage());
}
if(jp.existsById(entity.getId())) {
System.out.println("删除失败");
return Information.NewFail("删除失败");
}
return Information.NewSuccess(response);
}
// 复制非空属性(忽略关联字段)
private void copyNonNullProperties(Object source, Object target)
throws IllegalAccessException {
Class<?> clazz = source.getClass();
for (Field field : clazz.getDeclaredFields()) {
field.setAccessible(true);
Object value = field.get(source);
// 跳过关联字段和特殊字段
if (value != null &&
!isEntityBasisField(field) &&
!isCollectionField(field) &&
!field.getName().equals("id")) {
Field targetField;
try {
targetField = target.getClass().getDeclaredField(field.getName());
targetField.setAccessible(true);
targetField.set(target, value);
} catch (NoSuchFieldException e) {
// 忽略不存在的字段
}
}
}
}
// 检查是否为关联实体字段
private boolean isEntityBasisField(Field field) {
return EntityBasis.class.isAssignableFrom(field.getType());
}
// 检查是否为集合字段
private boolean isCollectionField(Field field) {
return Collection.class.isAssignableFrom(field.getType()) ||
Map.class.isAssignableFrom(field.getType());
}
/**
* 根据非空属性值动态查询实体
* @param entity 包含查询条件的实体对象(非空属性作为查询条件)
* @return 查询结果信息(成功时包含数据列表)
*/
public <T>Information getSELECTEntity(T entity) {
if (entity == null) {
return Information.NewFail("查询参数不能为空");
}
Class<T> entityClass = (Class<T>) entity.getClass();
try {
// 1. 获取非泛型的Repository
JpaRepository repository = repositoryService.getJpaRepository(entityClass);
// 2. 构建非泛型的Example查询
ExampleMatcher matcher = ExampleMatcher.matching()
.withIgnoreNullValues()
.withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING);
// 这里直接使用原始类型Example
Example<T> example = Example.of(entity);//he type Example is not generic; it cannot be parameterized with arguments <T>the method of(T) is undefined for the type Example
// 3. 执行查询
List<?> result = repository.findAll(example);
return Information.NewSuccess(result);
} catch (ClassCastException e) {
return Information.NewFail("Repository类型不匹配: " + e.getMessage());
} catch (DataAccessException e) {
return Information.NewFail("数据库访问错误: " + e.getMessage());
} catch (Exception e) {
return Information.NewFail("系统错误: " + e.getMessage());
}
}
private List<Map<String, Object>> convertEntityBasis(List<EntityBasis> entities) {
return entities.stream().map(entity -> {
Map<String, Object> map = new HashMap<>();
Field[] fields = entity.getClass().getDeclaredFields();
try {
// 添加实体自身的基本字段
map.put("id", entity.getId());
// 处理所有字段
for (Field field : fields) {
field.setAccessible(true); // 允许访问私有字段
Object fieldValue = field.get(entity);
if (fieldValue != null) {
String fieldName = field.getName();
// 处理集合类型关联
if (isCollection(field)) {
if (!((Collection<?>) fieldValue).isEmpty()) {
List<Map<String, Object>> collectionItems = ((Collection<?>) fieldValue)
.stream()
.filter(item -> item instanceof EntityBasis)
.map(item -> {
Map<String, Object> itemMap = new HashMap<>();
itemMap.put("id", ((EntityBasis) item).getId());
return itemMap;
})
.collect(Collectors.toList());
map.put(fieldName, collectionItems);
}
}
// 处理单个实体关联
else if (implementsInterface(field, EntityBasis.class)) {
Map<String, Object> associatedMap = new HashMap<>();
associatedMap.put("id", ((EntityBasis) fieldValue).getId());
map.put(fieldName, associatedMap);
}
// 处理其他基本类型字段
else if (!isSpecialField(fieldName)) {
map.put(fieldName, fieldValue);
}
}
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return map;
}).collect(Collectors.toList());
}
// 判断是否为特殊字段(需要排除的字段)
private boolean isSpecialField(String fieldName) {
return fieldName.equals("handler") || fieldName.equals("hibernateLazyInitializer");
}
/**
*-判断属性是否为集合类型
* @param field
* @return
*/
boolean isCollection(Field field) {
Class<?> type = field.getType();
// 检查是否为Java内置集合类型
if (Collection.class.isAssignableFrom(type) ||
Map.class.isAssignableFrom(type) ||
type.isArray()) {
return true;
}
// 检查是否实现集合相关接口(如Iterable)
for (Class<?> interfaceType : type.getInterfaces()) {
if (Iterable.class.isAssignableFrom(interfaceType)) {
return true;
}
}
return false;
}
/**
* -判断属性是否实现特定接口
* @param field
* @param targetInterface
* @return
*/
boolean implementsInterface(Field field, Class<?> targetInterface) {
Class<?> type = field.getType();
// 检查类本身是否实现接口
if (targetInterface.isAssignableFrom(type)) {
return true;
}
// 检查实现的接口是否继承目标接口
for (Class<?> interfaceType : type.getInterfaces()) {
if (targetInterface.isAssignableFrom(interfaceType)) {
return true;
}
}
return false;
}
private Object convertDingdanChanpins(List<Dingdan_chanpin> findAll) {
// TODO Auto-generated method stub
return null;
}
private Object convertDingdanChanpinZujians(List<Dingdan_chanpin_zujian> findAll) {
// TODO Auto-generated method stub
return null;
}
}
package com.kucun.Service;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;
@Service
public class DynamicRepositoryService {
private final Map<Class<?>, JpaRepository<?, ?>> repositoryMap = new HashMap<>();
private final Map<String, JpaRepository<?, ?>> repositoryNameMap = new HashMap<>();
public Map<String, JpaRepository<?, ?>> getRepositoryNameMap() {
return repositoryNameMap;
}
public Map<Class<?>, JpaRepository<?, ?>> getRepositoryMap() {
return repositoryMap;
}
public JpaRepository<?,?> getJpaRepository(String e){
// System.out.println("String:"+e+mapToString(repositoryNameMap));
return repositoryNameMap.get(e);
}
public JpaRepository<?,?> getJpaRepository(Class<?> e){
// System.out.println("Class:"+e+mapToString(repositoryMap));
// System.out.println("Class:"+e);
return repositoryMap.get(e);
}
// 自动注入所有JpaRepository实例
@Autowired
public void initRepositories(Map<String, JpaRepository<?, ?>> repositories) {
repositories.forEach((name, repo) -> {
// 获取代理类实现的接口
Class<?>[] interfaces = repo.getClass().getInterfaces();
for (Class<?> iface : interfaces) {
// 扫描接口上的泛型信息
Type[] genericInterfaces = iface.getGenericInterfaces();
for (Type type : genericInterfaces) {
if (type instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) type;
// 检查原始类型是否是JpaRepository
if (pt.getRawType().equals(JpaRepository.class)) {
Type[] args = pt.getActualTypeArguments();
if (args.length >= 2 && args[0] instanceof Class) {
Class<?> entityClass = (Class<?>) args[0];
repositoryMap.put(entityClass, repo);
String key = entityClass.getSimpleName().toLowerCase();
repositoryNameMap.put(key, repo);
// 调试日志
System.out.printf("Mapped %s -> %s [key: %s]%n",
entityClass.getName(),
repo.getClass().getName(),
key);
}
}
}
}
// 检查接口本身的泛型签名(如果继承的是参数化接口)
Type genericSuper = iface.getGenericSuperclass();
if (genericSuper instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) genericSuper;
if (pt.getRawType().equals(JpaRepository.class)) {
Type[] args = pt.getActualTypeArguments();
if (args.length >= 2 && args[0] instanceof Class) {
Class<?> entityClass = (Class<?>) args[0];
repositoryMap.put(entityClass, repo);
String key = entityClass.getSimpleName().toLowerCase();
repositoryNameMap.put(key, repo);
// 调试日志
System.out.printf("Mapped %s -> %s [key: %s]%n",
entityClass.getName(),
repo.getClass().getName(),
key);
}
}
}
}
});
}
// 通用保存方法
public <T> T saveEntity(T entity) {
JpaRepository<T, ?> repo = (JpaRepository<T, ?>) repositoryMap.get(entity.getClass());
if (repo != null) {
return repo.save(entity);
}
throw new IllegalArgumentException("Repository not found for " + entity.getClass());
}
public static String mapToString(Map<?, ?> map) {
if (map == null || map.isEmpty()) {
return "";
}
StringBuilder sb = new StringBuilder();
for (Map.Entry<?, ?> entry : map.entrySet()) {
sb.append(entry.getKey()).append("=").append(entry.getValue()).append(",");
}
// 删除最后一个多余的逗号
if (sb.length() > 0) {
sb.setLength(sb.length() - 1);
}
return sb.toString();
}
}package com.kucun.Service;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.metamodel.*;
import org.springframework.stereotype.Service;
import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;
@Service
public class EntityDependencyService {
@PersistenceContext
private EntityManager entityManager;
private final Map<Class<?>, Set<Attribute<?, ?>>> associationCache = new HashMap<>();
/**
* 检查实体是否被其他实体引用
* @param entityClass 实体类
* @param entityId 实体ID
* @return 存在引用返回true
*/
public boolean hasDependencies(Class<?> entityClass, Serializable entityId) {
Metamodel metamodel = entityManager.getMetamodel();
Set<EntityType<?>> entities = metamodel.getEntities();
for (EntityType<?> entityType : entities) {
// 跳过自身(避免自引用检查)
if (entityType.getJavaType().equals(entityClass)) continue;
Set<Attribute<?, ?>> associations = getAssociationAttributes(entityType);
for (Attribute<?, ?> attr : associations) {
if (attr.getJavaType().isAssignableFrom(entityClass)) {
if (isReferenced(entityType, attr, entityId)) {
return true;
}
}
}
}
return false;
}
/**
* 获取实体所有关联属性(带缓存)
*/
private Set<Attribute<?, ?>> getAssociationAttributes(EntityType<?> entityType) {
return associationCache.computeIfAbsent(entityType.getJavaType(), k ->
entityType.getAttributes().stream()
.filter(Attribute::isAssociation)
.collect(Collectors.toSet())
);
}
/**
* 检查特定关联是否引用目标实体
*/
private boolean isReferenced(EntityType<?> entityType, Attribute<?, ?> attribute, Serializable targetId) {
String jpql = buildReferenceQuery(entityType, attribute);
Long count = (Long) entityManager.createQuery(jpql)
.setParameter("targetId", targetId)
.getSingleResult();
return count > 0;
}
/**
* 构建引用检查查询
*/
private String buildReferenceQuery(EntityType<?> entityType, Attribute<?, ?> attribute) {
String entityName = entityType.getName();
String attrName = attribute.getName();
if (attribute instanceof PluralAttribute) {
return String.format("SELECT COUNT(e) FROM %s e WHERE :targetId MEMBER OF e.%s",
entityName, attrName);
} else {
return String.format("SELECT COUNT(e) FROM %s e WHERE e.%s.id = :targetId",
entityName, attrName);
}
}
}完善删除功能尽量简洁
最新发布