@Service
@RequiredArgsConstructor
@Slf4j
public class ProductInitTask implements ApplicationRunner {
private final NetTypeRepository netTypeRepository;
private final ProtocolTypeRepository protocolTypeRepository;
private final CategoryRepository categoryRepository;
@Override
public void run(ApplicationArguments args) throws Exception {
// 检查是否已存在预定义的文档
if (netTypeRepository.count() == 0) {
// 如果不存在,则创建
initializeNetTypes();
}
if (protocolTypeRepository.count() == 0) {
initializeProtocolTypes();
}
if (categoryRepository.count() == 0) {
initializeCategory();
}
}
private void initializeNetTypes() {
String[] predefinedNetTypes = {"WiFi", "NB-IoT", "蜂窝(2G/3G/4G/5G)", "以太网", "其他"};
for (String netType : predefinedNetTypes) {
NetType newNetType = new NetType();
newNetType.setNetType(netType);
try {
netTypeRepository.save(newNetType);
}catch (Exception e) {
log.error("netType数据库异常" + e);
throw new ServiceException(
ServiceException.ExceptionType.INTERNAL_FAILURE,
ExceptionInfoBuilder.build(ExceptionTemplate.INTERNAL_FAILURE_DATABASE, "数据库保存netType类型")
);
}
}
}
private void initializeProtocolTypes() {
String[] predefinedProtocolTypes = {"OPC", "LoRa", "BLE", "ZigeBee", "自定义"};
for (String protocolType : predefinedProtocolTypes) {
ProtocolType newProtocolType = new ProtocolType();
newProtocolType.setProtocolType(protocolType);
try {
protocolTypeRepository.save(newProtocolType);
}catch (Exception e) {
log.error("protocol数据库异常" + e);
throw new ServiceException(
ServiceException.ExceptionType.INTERNAL_FAILURE,
ExceptionInfoBuilder.build(ExceptionTemplate.INTERNAL_FAILURE_DATABASE, "数据库保存protocol类型")
);
}
}
}
private void initializeCategory() {
String[] predefinedCategory = {"物联网水表", "流量计", "压力计", "水质检测仪", "光电直读水表","电磁大表","超声波水表","其他"};
for (String category : predefinedCategory) {
Category newCategory = new Category();
newCategory.setCategory(category);
try {
categoryRepository.save(newCategory);
}catch (Exception e) {
log.error("category数据库异常" + e);
throw new ServiceException(
ServiceException.ExceptionType.INTERNAL_FAILURE,
ExceptionInfoBuilder.build(ExceptionTemplate.INTERNAL_FAILURE_DATABASE, "数据库保存category类型")
);
}
}
}
}
自动生成数据库中的表,注意要考虑每次重启服务时做了什么事想要什么效果;
如果不需要灵活可随时添加新数据的表的话,则可以用枚举计不用像这样麻烦了;