GenericEntityService extends AbstractService<E, PK> implements GenericService<E, PK> { @Override public PK insert(E entity) { if (!StringUtils.isEmpty(entity.getId())) { if ((entity.getId() instanceof String) && !StringUtils.isEmpty(entity.getId())) { tryValidateProperty(entity.getId().toString().matches("[a-zA-Z0-9_\\-]+"), "id", "只能由数字,字母,下划线,和-组成"); } tryValidateProperty(selectByPk(entity.getId()) == null, "id", entity.getId() + "已存在"); } if (StringUtils.isEmpty(entity.getId()) && getIDGenerator() != null) { entity.setId(getIDGenerator().generate()); } if (entity instanceof RecordCreationEntity) { ((RecordCreationEntity) entity).setCreateTimeNow(); } tryValidate(entity, CreateGroup.class); getDao().insert(entity); if (eventPublisher != null && pushCreatedEvent()) { eventPublisher.publishEvent(new GenericsPayloadApplicationEvent<>(this, new EntityCreatedEvent<>(entity, getEntityType()), getEntityType())); } return entity.getId(); } @SuppressWarnings("unchecked")  GenericEntityService(); @Autowired(required = false) void setEventPublisher(ApplicationEventPublisher eventPublisher); @PostConstruct void init(); @Override E deleteByPk(PK pk); @Override int updateByPk(PK pk, E entity); @Override int updateByPk(List<E> data); @Override PK saveOrUpdate(E entity); @Override PK insert(E entity); @Override @Transactional(readOnly = true) E selectByPk(PK pk); @Override @Transactional(readOnly = true) List<E> selectByPk(List<PK> id);  }
@Test public void testInsert() { TestEntity testEntity = TestEntity.builder() .age((byte) 1) .enabled(true) .build(); try { entityService.insert(testEntity); Assert.assertFalse(true); } catch (ValidationException e) { Assert.assertFalse(e.getResults().isEmpty()); Assert.assertEquals(e.getResults().get(0).getField(), "name"); testEntity.setId(null); } testEntity.setName("测试"); String id = entityService.insert(testEntity); Assert.assertNotNull(id); }