package com.kucun.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kucun.Service.AppService;
import com.kucun.data.entity.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/app")
public class AppController {
// Java 8 兼容的实体类型映射
private static final Map<String, Class<?>> ENTITY_MAP;
static {
Map<String, Class<?>> map = new HashMap<>();
map.put("user", User.class);
map.put("bancai", Bancai.class);
map.put("caizi", Caizhi.class);
map.put("mupi", Mupi.class);
map.put("dingdan", Dingdan.class);
map.put("zujian", Zujian.class);
map.put("chanpin", Chanpin.class);
map.put("dingdan_chanpin", Dingdan_chanpin.class);
map.put("dingdan_chanpin_zujian", Dingdan_chanpin_zujian.class);
map.put("chanpin_zujian", Chanpin_zujian.class);
map.put("jinhuo", Jinhuo.class);
map.put("kucun", Kucun.class);
ENTITY_MAP = Collections.unmodifiableMap(map);
}
@Autowired
private AppService appService;
@Autowired
private ObjectMapper objectMapper;
// ====================== 数据查询 ======================
@GetMapping("/all")
public Information getAllData() {
return appService.getAllData();
}
@GetMapping("/all/{entityType}")
public Information getEntityData(@PathVariable String entityType) {
return appService.getEntityData(entityType.toLowerCase());
}
// ====================== CRUD操作 ======================
@PostMapping("/add/{entityType}")
public Information addEntity(
@PathVariable String entityType,
@RequestBody Map<String, Object> requestBody
) {
return handleEntityOperation(entityType, requestBody, "add");
}
@PostMapping("/select/{entityType}")
public Information queryEntity(
@PathVariable String entityType,
@RequestBody Map<String, Object> requestBody
) {
return handleEntityOperation(entityType, requestBody, "select");
}
@PostMapping("/delete/{entityType}")
public Information deleteEntity(
@PathVariable String entityType,
@RequestBody Map<String, Object> requestBody
) {
return handleEntityOperation(entityType, requestBody, "delete");
}
@PostMapping("/update/{entityType}")
public Information updateEntity(
@PathVariable String entityType,
@RequestBody Map<String, Object> requestBody
) {
return handleEntityOperation(entityType, requestBody, "update");
}
// ====================== 核心辅助方法 ======================
private Information handleEntityOperation(
String entityType,
Map<String, Object> requestBody,
String operation
) {
String normalizedType = entityType.toLowerCase();
Class<?> entityClass = ENTITY_MAP.get(normalizedType);
if (entityClass == null) {
return Information.NewFail("不支持的实体类型: " + entityType);
}
try {
Object entity = objectMapper.convertValue(requestBody, entityClass);
switch (operation) {
case "add":
return appService.addEntity(entity);
case "select":
return appService.queryEntity(entity);
case "delete":
// 确保实体实现了EntityBasis接口
if (entity instanceof EntityBasis) {
return appService.deleteEntity((EntityBasis) entity);
} else {
return Information.NewFail("删除操作需要实体实现EntityBasis接口");
}
case "update":
return appService.updateEntity(entity);
default:
return Information.NewFail("无效的操作类型");
}
} catch (Exception e) {
return Information.NewFail(operation + "操作失败: " + e.getMessage());
}
}
}package com.kucun.Service;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.*;
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.*;
import com.kucun.dataDo.*;
@Service
public class AppService {
// 自动注入所有依赖
@Autowired private KucunRepository kucunRepository;
@Autowired private DynamicRepositoryService repositoryService;
@Autowired private EntityDependencyService dependencyService;
/**
* 获取所有实体类型的数据
* @return 包含所有实体数据的Map
*/
public Information getAllData() {
Map<String, Object> response = new HashMap<>();
repositoryService.getRepositoryNameMap().forEach((key, repo) ->
response.put(key + "s", repo.findAll())
);
return Information.NewSuccess(response);
}
/**
* 获取指定实体类型的所有数据
* @param entityName 实体名称
* @return 实体数据列表
*/
public Information getEntityData(String entityName) {
JpaRepository<?, ?> repo = repositoryService.getJpaRepository(entityName);
return Information.NewSuccess(repo.findAll());
}
/**
* 添加新实体
* @param entity 要添加的实体对象
* @return 添加结果
*/
public Information addEntity(Object entity) {
try {
// 处理关联字段
handleAssociations(entity);
// 获取对应的Repository并保存
JpaRepository<Object, Serializable> repo =
(JpaRepository<Object, Serializable>) repositoryService.getJpaRepository(entity.getClass());
Object savedEntity = repo.save(entity);
// 如果是板材,初始化库存
if (savedEntity instanceof Bancai) {
initializeKucunForBancai((Bancai) savedEntity);
}
return Information.NewSuccess(savedEntity);
} catch (Exception ex) {
return Information.Newfail(500, "创建失败: " + ex.getMessage(), null);
}
}
/**
* 更新实体
* @param entity 包含ID的实体对象
* @return 更新结果
*/
public Information updateEntity(Object entity) {
if (entity == null) {
return Information.Newfail(403, "参数为空", null);
}
try {
// 获取ID字段
Field idField = entity.getClass().getDeclaredField("id");
idField.setAccessible(true);
Object idValue = idField.get(entity);
if (idValue == null) {
return Information.Newfail(403, "ID为空", null);
}
// 获取Repository和现有实体
JpaRepository<Object, Serializable> repo =
(JpaRepository<Object, Serializable>) repositoryService.getJpaRepository(entity.getClass());
Object existingEntity = repo.findById((Serializable) idValue)
.orElseThrow(() -> new RuntimeException("实体不存在"));
// 复制非空属性并保存
copyNonNullProperties(entity, existingEntity);
return Information.NewSuccess(repo.save(existingEntity));
} catch (Exception ex) {
return Information.Newfail(500, "更新失败: " + ex.getMessage(), null);
}
}
/**
* 删除实体
* @param entity 要删除的实体
* @return 删除结果
*/
public Information deleteEntity(EntityBasis entity) {
if (entity == null) {
return Information.NewFail("删除对象不能为空");
}
try {
String entityName = entity.getClass().getSimpleName().toLowerCase();
JpaRepository<Object, Serializable> repo =
(JpaRepository<Object, Serializable>) repositoryService.getJpaRepository(entityName);
// 检查实体是否存在
if (!repo.existsById(entity.getId())) {
return Information.NewFail("未找到ID为" + entity.getId() + "的" + entityName);
}
// 检查依赖关系
if (dependencyService.hasDependencies(entity.getClass(), entity.getId())) {
return Information.NewFail("该记录已被引用,无法删除");
}
// 执行删除并验证
repo.deleteById(entity.getId());
if (repo.existsById(entity.getId())) {
return Information.NewFail("删除失败");
}
return Information.NewSuccess("删除成功");
} catch (Exception e) {
return Information.NewFail("删除错误: " + e.getMessage());
}
}
/**
* 动态查询实体
* @param entity 包含查询条件的实体对象
* @return 查询结果
*/
public <T> Information queryEntity(T entity) {
if (entity == null) {
return Information.NewFail("查询参数不能为空");
}
try {
JpaRepository<T, ?> repo = (JpaRepository<T, ?>) repositoryService.getJpaRepository(entity.getClass());
Example<T> example = Example.of(entity, ExampleMatcher.matching()
.withIgnoreNullValues()
.withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING));
return Information.NewSuccess(repo.findAll(example));
} catch (Exception e) {
return Information.NewFail("查询失败: " + e.getMessage());
}
}
// ====================== 私有辅助方法 ======================
/**
* 为板材初始化库存
* @param bancai 板材对象
*/
private void initializeKucunForBancai(Bancai bancai) throws Exception {
Kucun kucun = new Kucun(null, bancai, 0);
bancai.setKucun(kucunRepository.save(kucun));
}
/**
* 处理实体关联关系
* @param entity 要处理的实体
*/
private void handleAssociations(Object entity) throws Exception {
for (Field field : entity.getClass().getDeclaredFields()) {
field.setAccessible(true);
Object value = field.get(entity);
if (value == null) continue;
// 处理单个实体关联
if (value instanceof EntityBasis) {
EntityBasis associated = (EntityBasis) value;
JpaRepository<Object, Serializable> repo =
(JpaRepository<Object, Serializable>) repositoryService.getJpaRepository(associated.getClass());
// 修复:添加异常供应器
field.set(entity, repo.findById(associated.getId())
.orElseThrow(() -> new RuntimeException("关联实体不存在")));
}
// 处理集合关联
else if (value instanceof Collection) {
List<Object> managedEntities = new ArrayList<>();
for (Object item : (Collection<?>) value) {
if (item instanceof EntityBasis) {
EntityBasis eb = (EntityBasis) item;
JpaRepository<Object, Serializable> repo =
(JpaRepository<Object, Serializable>) repositoryService.getJpaRepository(eb.getClass());
// 修复:添加异常供应器
managedEntities.add(repo.findById(eb.getId())
.orElseThrow(() -> new RuntimeException("关联实体不存在")));
}
}
if (!managedEntities.isEmpty()) {
field.set(entity, managedEntities);
}
}
}
}
/**
* 复制非空属性
* @param source 源对象
* @param target 目标对象
*/
private void copyNonNullProperties(Object source, Object target) throws IllegalAccessException {
for (Field field : source.getClass().getDeclaredFields()) {
field.setAccessible(true);
Object value = field.get(source);
// 跳过关联字段和ID字段
if (value != null &&
!(value instanceof EntityBasis) &&
!(value instanceof Collection) &&
!field.getName().equals("id")) {
try {
Field targetField = target.getClass().getDeclaredField(field.getName());
targetField.setAccessible(true);
targetField.set(target, value);
} catch (NoSuchFieldException ignored) {}
}
}
}
}package com.kucun.data.entity;
import java.lang.annotation.Annotation;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import com.kucun.data.entity.DTO.*;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
/**
* 板材
* @author Administrator
*
*/
@Entity
@Table(name="bancai")
@JsonSerialize(using = FullEntitySerializer.class)
public class Bancai implements EntityBasis {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "caizhi_id") //
private Caizhi caizhi;
@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "mupi1_id")
private Mupi mupi1;
@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "mupi2_id")
private Mupi mupi2;
private Double houdu;
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "kucun_id", referencedColumnName = "id")
private Kucun kucun;
public Kucun getKucun() {
return kucun;
}
public void setKucun(Kucun kucun) {
this.kucun = kucun;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Caizhi getCaizhi() {
return caizhi;
}
public void setCaizhi(Caizhi caizhi) {
this.caizhi = caizhi;
}
public Mupi getMupi1() {
return mupi1;
}
public void setMupi1(Mupi mupi1) {
this.mupi1 = mupi1;
}
public Mupi getMupi2() {
return mupi2;
}
public void setMupi2(Mupi mupi2) {
this.mupi2 = mupi2;
}
public Double getHoudu() {
return houdu;
}
public void setHoudu(Double houdu) {
this.houdu = houdu;
}
public Bancai(int id, Caizhi caizhi, Mupi mupi1, Mupi mupi2, Double houdu) {
super();
this.id = id;
this.caizhi = caizhi;
this.mupi1 = mupi1;
this.mupi2 = mupi2;
this.houdu = houdu;
}
public Bancai() {
super();
}
}
package com.kucun.data.entity;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.kucun.data.entity.DTO.FullEntitySerializer;
/**
* 板材材质
* @author Administrator
*
*/
@Entity
@Table(name="caizhi", uniqueConstraints = {
@UniqueConstraint(columnNames = "name")
})
@JsonSerialize(using = FullEntitySerializer.class)
public class Caizhi extends SimpleEntity implements EntityBasis{
@OneToMany(mappedBy="caizhi")
private List<Bancai> bancais;
public Caizhi() {
super();
}
// 添加反向关联维护方法
public void addBancai(Bancai bancai) {
bancais.add(bancai);
bancai.setCaizhi(this);
}
// 添加移除方法
public void removeBancai(Bancai bancai) {
bancais.remove(bancai);
bancai.setCaizhi(null);
}
public List<Bancai> getBancais() {
return bancais;
}
public void setBancais(List<Bancai> bancais) {
this.bancais = bancais;
}
}
http://127.0.0.1:8080/KuCun2/app/delete/bancai {"id":10}
删除错误: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
最新发布