ClassNotFound javax.persistence.cacheable

本文将指导您如何解决在使用JPA2.0规范时遇到的ClassNotFound javax.persistence.cacheable错误,通过将hibernate-jpa-2.0-api-1.0.0.Final.jar加入路径中来解决此问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

错误:

	ClassNotFound javax.persistence.cacheable

解决方法:

	javax.persistence.Cacheable 是 JPA 2.0 规范中的
	需要加入hibernate-distribution-3.5.0-Final\lib\jpa目录下的hibernate-jpa-2.0-api-1.0.0.Final.jar到path中

 

 

 

 

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.Set; import java.util.stream.Collectors; import javax.persistence.metamodel.Attribute; import javax.persistence.metamodel.EntityType; import javax.persistence.metamodel.Metamodel; import javax.persistence.metamodel.PluralAttribute; 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.Caizhi; import com.kucun.data.entity.Chanpin; import com.kucun.data.entity.Chanpin_zujian; import com.kucun.data.entity.Dingdan; 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.data.entity.Mupi; import com.kucun.data.entity.User; import com.kucun.data.entity.Zujian; 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; // private Map<String, JpaRepository<?, ?>> shiti; // // // @Override // public void setApplicationContext(ApplicationContext context) { // this.shiti = getJpaRepositories(context); // } // // public Map<String, JpaRepository<?, ?>> getJpaRepositories(ApplicationContext context) { // return context.getBeansWithAnnotation(Repository.class) // .entrySet() // .stream() // .filter(entry -> entry.getValue() instanceof JpaRepository) // .collect(Collectors.toMap( // entry -> { // JpaRepository<?, ?> repo = (JpaRepository<?, ?>) entry.getValue(); // return getEntityClass(repo).getName(); // }, // entry -> (JpaRepository<?, ?>) entry.getValue() // )); // } // // public static Class<?> getEntityClass(JpaRepository<?, ?> repo) { // try { // // 处理Spring代理类 // Object target = repo; // while (target instanceof Advised) { // target = ((Advised) target).getTargetSource().getTarget(); // } // // // 通过Spring的ResolvableType解析泛型 // ResolvableType resolvableType = ResolvableType.forClass( // target.getClass()).as(JpaRepository.class); // // if (resolvableType.getGenerics().length > 0) { // Class<?> entityClass = resolvableType.getGeneric(0).resolve(); // if (entityClass != null) { // return entityClass; // } // } // // throw new IllegalStateException("无法解析实体类型"); // } catch (Exception e) { // throw new RuntimeException("获取实体类失败: " + e.getMessage(), e); // } // } // // public Information getAllDataWithChildIdse() { // Map<String, Object> response = new HashMap<>(); // // response.put("caizhis", (caizhiRepository.findAll())); // response.put("bancais", (bancaiRepository.findAll())); // response.put("chanpins", (chanpinRepository.findAll())); // response.put("dingdans", (dingdanRepository.findAll())); // response.put("mupis", (mupiRepository.findAll())); // response.put("zujians", (zujianRepository.findAll())); // response.put("kucuns", (kucunRepository.findAll())); // response.put("users", (userRepository.findAll())); // response.put("chanpin_zujians", (chanpinZujianRepository.findAll())); // response.put("chanpin_zujians", (dingdanChanpinZujianRepository.findAll())); // response.put("chanpin_zujians", (dingdanChanpinRepository.findAll())); // // return Information.NewSuccess(response); // } 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; } } 删除功能完善
06-18
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值