首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >MongoRepository保存方法未插入到数据库中

MongoRepository保存方法未插入到数据库中
EN

Stack Overflow用户
提问于 2021-07-09 04:13:30
回答 1查看 109关注 0票数 0

我和Jhipster一起创建了一个SpringBoot项目。我使用的数据库是MongoDB。

在application-dev.yml中,我有以下配置:

代码语言:javascript
复制
data:
mongodb:
  uri: mongodb://<user>:<pass>@<ip>:<port>
  database: gateway

我的application-dev中的用户、密码、ip地址和端口是实值。

DatabaseConfiguration.java为:

代码语言:javascript
复制
@Configuration
@EnableMongoRepositories("es.second.cdti.repository")
@Profile("!" + JHipsterConstants.SPRING_PROFILE_CLOUD)
@Import(value = MongoAutoConfiguration.class)
@EnableMongoAuditing(auditorAwareRef = "springSecurityAuditorAware")
public class DatabaseConfiguration {

    private final Logger log = LoggerFactory.getLogger(DatabaseConfiguration.class);

    @Bean
    public ValidatingMongoEventListener validatingMongoEventListener() {
        return new ValidatingMongoEventListener(validator());
    }

    @Bean
    public LocalValidatorFactoryBean validator() {
        return new LocalValidatorFactoryBean();
    }

    @Bean
    public MongoCustomConversions customConversions() {
        List<Converter<?, ?>> converters = new ArrayList<>();
        converters.add(DateToZonedDateTimeConverter.INSTANCE);
        converters.add(ZonedDateTimeToDateConverter.INSTANCE);
        return new MongoCustomConversions(converters);
    }

    @Bean
    public Mongobee mongobee(MongoClient mongoClient, MongoTemplate mongoTemplate, MongoProperties mongoProperties) {
        log.debug("Configuring Mongobee");
        Mongobee mongobee = new Mongobee(mongoClient);
        mongobee.setDbName(mongoProperties.getMongoClientDatabase());
        mongobee.setMongoTemplate(mongoTemplate);
        // package to scan for migrations
        mongobee.setChangeLogsScanPackage("es.second.cdti.config.dbmigrations");
        mongobee.setEnabled(true);
        return mongobee;
    }}

CloudDatabaseConfiguration为:

代码语言:javascript
复制
@Configuration
@EnableMongoRepositories("es.second.cdti.repository")
@Profile(JHipsterConstants.SPRING_PROFILE_CLOUD)
public class CloudDatabaseConfiguration extends AbstractCloudConfig {

    private final Logger log = LoggerFactory.getLogger(CloudDatabaseConfiguration.class);

    @Bean
    public MongoDbFactory mongoFactory() {
        return connectionFactory().mongoDbFactory();
    }

    @Bean
    public LocalValidatorFactoryBean validator() {
        return new LocalValidatorFactoryBean();
    }

    @Bean
    public ValidatingMongoEventListener validatingMongoEventListener() {
        return new ValidatingMongoEventListener(validator());
    }

    @Bean
    public MongoCustomConversions customConversions() {
        List<Converter<?, ?>> converterList = new ArrayList<>();
        converterList.add(DateToZonedDateTimeConverter.INSTANCE);
        converterList.add(ZonedDateTimeToDateConverter.INSTANCE);
        converterList.add(DurationToLongConverter.INSTANCE);
        return new MongoCustomConversions(converterList);
    }

    @Bean
    public Mongobee mongobee(MongoDbFactory mongoDbFactory, MongoTemplate mongoTemplate, Cloud cloud) {
        log.debug("Configuring Cloud Mongobee");
        List<ServiceInfo> matchingServiceInfos = cloud.getServiceInfos(MongoDbFactory.class);

        if (matchingServiceInfos.size() != 1) {
            throw new CloudException("No unique service matching MongoDbFactory found. Expected 1, found "
                + matchingServiceInfos.size());
        }
        MongoServiceInfo info = (MongoServiceInfo) matchingServiceInfos.get(0);
        Mongobee mongobee = new Mongobee(info.getUri());
        mongobee.setDbName(mongoDbFactory.getDb().getName());
        mongobee.setMongoTemplate(mongoTemplate);
        // package to scan for migrations
        mongobee.setChangeLogsScanPackage("es.second.cdti.config.dbmigrations");
        mongobee.setEnabled(true);
        return mongobee;
    }
}

cdtiApp.java为:

代码语言:javascript
复制
@SpringBootApplication
@EnableConfigurationProperties({ApplicationProperties.class})
public class CdtiApp  implements InitializingBean{

    private static final Logger log = LoggerFactory.getLogger(CdtiApp.class);

    private final Environment env;

    public CdtiApp(Environment env) {
        this.env = env;
    }

    /**
     * Initializes cdti.
     * <p>
     * Spring profiles can be configured with a program argument --spring.profiles.active=your-active-profile
     * <p>
     * You can find more information on how profiles work with JHipster on <a href="https://www.jhipster.tech/profiles/">https://www.jhipster.tech/profiles/</a>.
     */
    @PostConstruct
    public void initApplication() {
        Collection<String> activeProfiles = Arrays.asList(env.getActiveProfiles());
        if (activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) && activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_PRODUCTION)) {
            log.error("You have misconfigured your application! It should not run " +
                "with both the 'dev' and 'prod' profiles at the same time.");
        }
        if (activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) && activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_CLOUD)) {
            log.error("You have misconfigured your application! It should not " +
                "run with both the 'dev' and 'cloud' profiles at the same time.");
        }
    }

    /**
     * Main method, used to run the application.
     *
     * @param args the command line arguments.
     */
    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(CdtiApp.class);
        DefaultProfileUtil.addDefaultProfile(app);
        Environment env = app.run(args).getEnvironment();
        logApplicationStartup(env);
    }

    private static void logApplicationStartup(Environment env) {
        String protocol = "http";
        if (env.getProperty("server.ssl.key-store") != null) {
            protocol = "https";
        }
        String serverPort = env.getProperty("server.port");
        String contextPath = env.getProperty("server.servlet.context-path");
        if (StringUtils.isBlank(contextPath)) {
            contextPath = "/";
        }
        String hostAddress = "localhost";
        try {
            hostAddress = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            log.warn("The host name could not be determined, using `localhost` as fallback");
        }
        log.info("\n----------------------------------------------------------\n\t" +
                "Application '{}' is running! Access URLs:\n\t" +
                "Local: \t\t{}://localhost:{}{}\n\t" +
                "External: \t{}://{}:{}{}\n\t" +
                "Profile(s): \t{}\n----------------------------------------------------------",
            env.getProperty("spring.application.name"),
            protocol,
            serverPort,
            contextPath,
            protocol,
            hostAddress,
            serverPort,
            contextPath,
            env.getActiveProfiles());

        String configServerStatus = env.getProperty("configserver.status");
        if (configServerStatus == null) {
            configServerStatus = "Not found or not setup for this application";
        }
        log.info("\n----------------------------------------------------------\n\t" +
                "Config Server: \t{}\n----------------------------------------------------------", configServerStatus);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        // TODO Auto-generated method stub
        
    }
}

车辆实体:

代码语言:javascript
复制
@org.springframework.data.mongodb.core.mapping.Document(collection = "vehicle")
public class Vehicle implements Serializable {
    
    private static final long serialVersionUID = 1L;

    @Id
    private String id;
    
    @NotNull
    @Field("plate")
    private String plate;
    
    @NotNull
    @Field("registrationDate")
    private Instant registrationDate;
    
    @NotNull
    @Field("brand")
    private String brand;
    
    @NotNull
    @Field("model")
    private String model;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getPlate() {
        return plate;
    }

    public void setPlate(String plate) {
        this.plate = plate;
    }

    public Instant getRegistrationDate() {
        return registrationDate;
    }

    public void setRegistrationDate(Instant registrationDate) {
        this.registrationDate = registrationDate;
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public String getModel() {
        return model;
    }

    public void setModel(String model) {
        this.model = model;
    }    

}

VehicleDTO为:

代码语言:javascript
复制
public class VehicleDTO {

    private String id;
    
    private String plate;
    
    private Instant registrationDate;
    
    private String brand;
    
    private String model;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getPlate() {
        return plate;
    }

    public void setPlate(String plate) {
        this.plate = plate;
    }

    public Instant getRegistrationDate() {
        return registrationDate;
    }

    public void setRegistrationDate(Instant registrationDate) {
        this.registrationDate = registrationDate;
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public String getModel() {
        return model;
    }

    public void setModel(String model) {
        this.model = model;
    }
    
    
}

VehicleMapper为:

代码语言:javascript
复制
@Mapper(componentModel = "spring")
public interface VehicleMapper{

    Vehicle toEntity(VehicleDTO source);
    VehicleDTO toDto(Vehicle target);
}

VehicleResource为:

代码语言:javascript
复制
@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "*", methods = { RequestMethod.GET, RequestMethod.POST })
public class VehicleResource {

    private final Logger log = LoggerFactory.getLogger(VehicleResource.class);

    @Value("${jhipster.clientApp.name}")
    private String applicationName;

    @Autowired
    private final VehicleService vehicleService;

    public VehicleResource(VehicleService vehicleService) {
        this.vehicleService = vehicleService;
    }

    @PostMapping("/vehicle")
    @PreAuthorize("hasAuthority(\"" + AuthoritiesConstants.ADMIN + "\")")
    public ResponseEntity<Vehicle> createVehicle(@Valid @RequestBody VehicleDTO vehicleDTO) throws URISyntaxException {
        log.debug("REST request to save Vehicle : {}", vehicleDTO);

        Vehicle newVehicle = vehicleService.createVehicle(vehicleDTO);

        return ResponseEntity.created(new URI("/api/vehicle/" + newVehicle.getPlate()))
                .headers(HeaderUtil.createAlert(applicationName, "vehicleManagement.created", newVehicle.getPlate()))
                .body(newVehicle);

    }
}

VehicleService接口为:

代码语言:javascript
复制
public interface VehicleService {

    Vehicle createVehicle(VehicleDTO vehicleDTO);
}

VehicleServiceImpl为:

代码语言:javascript
复制
@Service
public class VehicleServiceImpl implements VehicleService{
    
    @Autowired
    private final VehicleRepository vehicleRepository;
    
    @Autowired
    private final VehicleMapper mapper;
        
    public VehicleServiceImpl(VehicleRepository vehicleRepository, VehicleMapper mapper) {
        this.vehicleRepository = vehicleRepository;
        this.mapper = mapper;
    }

    private final Logger log = LoggerFactory.getLogger(VehicleServiceImpl.class);

    @Override
    public Vehicle createVehicle(VehicleDTO vehicleDTO) {
        
        Vehicle vehicle = vehicleRepository.save(mapper.toEntity(vehicleDTO));
        log.debug("Created Information for vehicle: {}", vehicle);
        
        return vehicle; 
    }
    

}

VehicleRepository接口为:

代码语言:javascript
复制
/**
 * Spring Data MongoDB repository for the {@link Vehicle} entity.
 */
@Repository
public interface VehicleRepository extends MongoRepository<Vehicle, String> {

}

从Swagger控制台访问Vehicle-Resource:Swagger console

单击该按钮并在文本框中写入带有车辆数据的json:enter JSON data

正如我们在下图中看到的,答案是201。最初使用标识符“id”保存车辆:"60e740935ed5a10e2c2ed19e“。Send request

我访问数据库以检查车辆是否已正确存储在vehicle表中。令我惊讶的是。vehicle表中没有车辆:show database

我可以确保数据库application-dev中的数据是正确的。我没有任何其他的数据库。

我怀疑与数据库的事务实际上并没有被执行。这些数据以某种方式存储在内存中,因为如果我从Swagger执行findAllVehicles,它会返回车辆。

EN

回答 1

Stack Overflow用户

发布于 2021-07-09 20:55:00

我有一个正在运行的eureka服务器(Jhipster Registry)和两个与之同步的微服务。网关,它充当反向代理和Vehiculos微服务。Swagger控制台是我请求插入车辆的入口。一切似乎都正常,但正如我在bbdd中所说的,它并没有保存任何东西。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68308102

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档