José d.
José d.

Reputation: 35

Why my Spring boot web APP IS not working? please

I'm trying to post web formulary results via Spring boot Web app to a MongoDB collection and i am having this error

:rd-00-01.wamjx.mongodb.net:27017 to client view of cluster
2021-07-21 09:56:19.691  INFO 9852 --- [mjx.mongodb.net] org.mongodb.driver.cluster               : Adding discovered server cluster0-shard-00-00.wamjx.mongodb.net:27017 to client view of cluster
2021-07-21 09:56:19.953  INFO 9852 --- [  restartedMain] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729
2021-07-21 09:56:20.078  WARN 9852 --- [  restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'productoServicioImplement': Unsatisfied dependency expressed through field 'productosRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'productosRepository' defined in com.example.ProductosRepository defined in @EnableMongoRepositories declared on MongoRepositoriesRegistrar.EnableMongoRepositoriesConfiguration: Invocation of init method failed; nested exception is org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract com.example.Producto com.example.ProductosRepository.getProductoById(java.lang.Integer)! Reason: No property id found for type Producto!; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property id found for type Producto!
2021-07-21 09:56:20.086  INFO 9852 --- [  restartedMain] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2021-07-21 09:56:20.118  INFO 9852 --- [  restartedMain] ConditionEvaluationReportLoggingListener : 

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-07-21 09:56:20.179 ERROR 9852 --- [  restartedMain] o.s.boot.SpringApplication               : Application run failed

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'productoServicioImplement': Unsatisfied dependency expressed through field 'productosRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'productosRepository' defined in com.example.ProductosRepository defined in @EnableMongoRepositories declared on MongoRepositoriesRegistrar.EnableMongoRepositoriesConfiguration: Invocation of init method failed; nested exception is org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract com.example.Producto com.example.ProductosRepository.getProductoById(java.lang.Integer)! Reason: No property id found for type Producto!; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property id found for type Producto!
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:660) ~[spring-beans-5.3.8.jar:5.3.8]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:640) ~[spring-beans-5.3.8.jar:5.3.8]
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:119) ~[spring-beans-5.3.8.jar:5.3.8]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399) ~[spring-beans-5.3.8.jar:5.3.8]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1413) ~[spring-beans-5.3.8.jar:5.3.8]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:601) ~[spring-beans-5.3.8.jar:5.3.8]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:524) ~[spring-beans-5.3.8.jar:5.3.8]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.8.jar:5.3.8]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.8.jar:5.3.8]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.8.jar:5.3.8]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.8.jar:5.3.8]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:944) ~[spring-beans-5.3.8.jar:5.3.8]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918) ~[spring-context-5.3.8.jar:5.3.8]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) ~[spring-context-5.3.8.jar:5.3.8]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145) ~[spring-boot-2.5.2.jar:2.5.2]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:754) [spring-boot-2.5.2.jar:2.5.2]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:434) [spring-boot-2.5.2.jar:2.5.2]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:338) [spring-boot-2.5.2.jar:2.5.2]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1343) [spring-boot-2.5.2.jar:2.5.2]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1332) [spring-boot-2.5.2.jar:2.5.2]
    at com.example.Main.main(Main.java:55) [classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_275]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_275]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_275]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_275]
    at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-2.5.2.jar:2.5.2]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'productosRepository' defined in com.example.ProductosRepository defined in @EnableMongoRepositories declared on MongoRepositoriesRegistrar.EnableMongoRepositoriesConfiguration: Invocation of init method failed; nested exception is org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract com.example.Producto com.example.ProductosRepository.getProductoById(java.lang.Integer)! Reason: No property id found for type Producto!; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property id found for type Producto!
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1786) ~[spring-beans-5.3.8.jar:5.3.8]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:602) ~[spring-beans-5.3.8.jar:5.3.8]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:524) ~[spring-beans-5.3.8.jar:5.3.8]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.8.jar:5.3.8]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.8.jar:5.3.8]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.8.jar:5.3.8]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.8.jar:5.3.8]
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276) ~[spring-beans-5.3.8.jar:5.3.8]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1380) ~[spring-beans-5.3.8.jar:5.3.8]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1300) ~[spring-beans-5.3.8.jar:5.3.8]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:657) ~[spring-beans-5.3.8.jar:5.3.8]
    ... 25 common frames omitted
Caused by: org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract com.example.Producto com.example.ProductosRepository.getProductoById(java.lang.Integer)! Reason: No property id found for type Producto!; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property id found for type Producto!
    at org.springframework.data.repository.query.QueryCreationException.create(QueryCreationException.java:101) ~[spring-data-commons-2.5.2.jar:2.5.2]
    at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.lookupQuery(QueryExecutorMethodInterceptor.java:106) ~[spring-data-commons-2.5.2.jar:2.5.2]
    at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.lambda$mapMethodsToQuery$1(QueryExecutorMethodInterceptor.java:94) ~[spring-data-commons-2.5.2.jar:2.5.2]
    at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193) ~[na:1.8.0_275]
    at java.util.Iterator.forEachRemaining(Iterator.java:116) ~[na:1.8.0_275]
    at java.util.Collections$UnmodifiableCollection$1.forEachRemaining(Collections.java:1051) ~[na:1.8.0_275]
    at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801) ~[na:1.8.0_275]
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:482) ~[na:1.8.0_275]
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:472) ~[na:1.8.0_275]
    at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708) ~[na:1.8.0_275]
    at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) ~[na:1.8.0_275]
    at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:566) ~[na:1.8.0_275]
    at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.mapMethodsToQuery(QueryExecutorMethodInterceptor.java:96) ~[spring-data-commons-2.5.2.jar:2.5.2]
    at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.lambda$new$0(QueryExecutorMethodInterceptor.java:86) ~[spring-data-commons-2.5.2.jar:2.5.2]
    at java.util.Optional.map(Optional.java:215) ~[na:1.8.0_275]
    at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.<init>(QueryExecutorMethodInterceptor.java:86) ~[spring-data-commons-2.5.2.jar:2.5.2]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:360) ~[spring-data-commons-2.5.2.jar:2.5.2]
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.lambda$afterPropertiesSet$5(RepositoryFactoryBeanSupport.java:323) ~[spring-data-commons-2.5.2.jar:2.5.2]
    at org.springframework.data.util.Lazy.getNullable(Lazy.java:230) ~[spring-data-commons-2.5.2.jar:2.5.2]
    at org.springframework.data.util.Lazy.get(Lazy.java:114) ~[spring-data-commons-2.5.2.jar:2.5.2]
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:329) ~[spring-data-commons-2.5.2.jar:2.5.2]
    at org.springframework.data.mongodb.repository.support.MongoRepositoryFactoryBean.afterPropertiesSet(MongoRepositoryFactoryBean.java:119) ~[spring-data-mongodb-3.2.2.jar:3.2.2]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1845) ~[spring-beans-5.3.8.jar:5.3.8]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1782) ~[spring-beans-5.3.8.jar:5.3.8]
    ... 35 common frames omitted
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property id found for type Producto!
    at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:90) ~[spring-data-commons-2.5.2.jar:2.5.2]
    at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:437) ~[spring-data-commons-2.5.2.jar:2.5.2]
    at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:413) ~[spring-data-commons-2.5.2.jar:2.5.2]
    at org.springframework.data.mapping.PropertyPath.lambda$from$0(PropertyPath.java:366) ~[spring-data-commons-2.5.2.jar:2.5.2]
    at java.util.concurrent.ConcurrentMap.computeIfAbsent(ConcurrentMap.java:324) ~[na:1.8.0_275]
    at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:348) ~[spring-data-commons-2.5.2.jar:2.5.2]
    at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:331) ~[spring-data-commons-2.5.2.jar:2.5.2]
    at org.springframework.data.repository.query.parser.Part.<init>(Part.java:81) ~[spring-data-commons-2.5.2.jar:2.5.2]
    at org.springframework.data.repository.query.parser.PartTree$OrPart.lambda$new$0(PartTree.java:249) ~[spring-data-commons-2.5.2.jar:2.5.2]
    at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193) ~[na:1.8.0_275]
    at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:175) ~[na:1.8.0_275]
    at java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948) ~[na:1.8.0_275]
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:482) ~[na:1.8.0_275]
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:472) ~[na:1.8.0_275]
    at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708) ~[na:1.8.0_275]
    at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) ~[na:1.8.0_275]
    at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:566) ~[na:1.8.0_275]
    at org.springframework.data.repository.query.parser.PartTree$OrPart.<init>(PartTree.java:250) ~[spring-data-commons-2.5.2.jar:2.5.2]
    at org.springframework.data.repository.query.parser.PartTree$Predicate.lambda$new$0(PartTree.java:383) ~[spring-data-commons-2.5.2.jar:2.5.2]
    at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193) ~[na:1.8.0_275]
    at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:175) ~[na:1.8.0_275]
    at java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948) ~[na:1.8.0_275]
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:482) ~[na:1.8.0_275]
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:472) ~[na:1.8.0_275]
    at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708) ~[na:1.8.0_275]
    at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) ~[na:1.8.0_275]
    at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:566) ~[na:1.8.0_275]
    at org.springframework.data.repository.query.parser.PartTree$Predicate.<init>(PartTree.java:384) ~[spring-data-commons-2.5.2.jar:2.5.2]
    at org.springframework.data.repository.query.parser.PartTree.<init>(PartTree.java:95) ~[spring-data-commons-2.5.2.jar:2.5.2]
    at org.springframework.data.mongodb.repository.query.PartTreeMongoQuery.<init>(PartTreeMongoQuery.java:67) ~[spring-data-mongodb-3.2.2.jar:3.2.2]
    at org.springframework.data.mongodb.repository.support.MongoRepositoryFactory$MongoQueryLookupStrategy.resolveQuery(MongoRepositoryFactory.java:207) ~[spring-data-mongodb-3.2.2.jar:3.2.2]
    at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.lookupQuery(QueryExecutorMethodInterceptor.java:102) ~[spring-data-commons-2.5.2.jar:2.5.2]
    ... 57 common frames omitted

------------------------------------------------------------------------
BUILD SUCCESS
------------------------------------------------------------------------

My objective is to send a query to the mongoDb table in my cluster()

This is my java code

Main.java

package com.example;


import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;


import javax.sql.DataSource;
import java.sql.SQLException;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration;




//@EnableAutoConfiguration
@ComponentScan

@SpringBootApplication
@EnableAutoConfiguration(exclude={MongoAutoConfiguration.class})
public class Main {

  @Value("${spring.datasource.url}")
  private String dbUrl;

  public static void main(String[] args) throws Exception {
    SpringApplication.run(Main.class, args);
    
        

    
  }
// 
  @Bean
  public DataSource dataSource() throws SQLException {
    if (dbUrl == null || dbUrl.isEmpty()) {
      return new HikariDataSource();
    } else {
      HikariConfig config = new HikariConfig();
      config.setJdbcUrl(dbUrl);
      return new HikariDataSource(config);
    }
  }

}

Producto.java

package com.example;


import java.io.Serializable;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Entity

@Document(collection = "productos")
@Table (name = "productos")
public class Producto {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column (name = "idProduct")
    @javax.persistence.Id
    private Integer idproducto;
    @Column (name = "stock")
    private String stock;
    @Column (name = "nombre")
    private String nombre;
    @Column (name = "codigo")
    private String codigo;
    @Column (name = "precio")
    private Double precio;
    @Column (name = "categoriaproducto")
    @OneToMany(mappedBy = "categoriaproducto")
    private categoriaProducto categoriaproducto;
    
    
    
    
   
    public Producto(){
      this.idproducto = 0;
      this.stock = "";
      this.nombre = "";
      this.codigo = "";
      this.precio = 0.0;
      this.categoriaproducto = categoriaProducto.frutas;
    }
    public Producto(Integer idd,String stockc, String nom, String cod, Double prec,categoriaProducto cgprod){
        super();
        this.idproducto = idd;
        this.stock = stockc;
        this.nombre = nom;
        this.codigo = cod;
        this.precio= prec;
        this.categoriaproducto=cgprod;
    }
    
    
    public Producto (Producto producto){
        super();
        this.idproducto = producto.idproducto;
        this.stock = producto.stock;
        this.nombre = producto.nombre;
        this.codigo = producto.codigo;
        this.precio = producto.precio;
        this.categoriaproducto = categoriaProducto.perecibles;
    }

    public Integer getIdproducto() {
        return idproducto;
    }

    public void setIdproducto(Integer idproducto) {
        this.idproducto = idproducto;
    }

    public String getStock() {
        return stock;
    }

    public void setStock(String stock) {
        this.stock = stock;
    }

    

    
    

    public String getNombre() {
        return nombre;
    }

    public void setNombre(String nombre) {
        this.nombre = nombre;
    }

    public String getCodigo() {
        return codigo;
    }

    public void setCodigo(String codigo) {
        this.codigo = codigo;
    }

    public Double getPrecio() {
        return precio;
    }

    public void setPrecio(Double precio) {
        this.precio = precio;
    }

    public categoriaProducto getCategoriaproducto() {
        return categoriaproducto;
    }

    public void setCategoriaproducto(categoriaProducto categoriaproducto) {
        this.categoriaproducto = categoriaproducto;
    }
    
    
    @Override
    public String toString(){
        return String.format(
        "Producto[stock =%s , nombre ='%s',codigo = '%s',precio =%s ,categoriaproducto = '%s' ]",
                stock,nombre,codigo,precio, categoriaproducto);
        
    }
}

ProductoServicio2.java

package com.example;

import java.util.List;

public abstract interface ProductoServicio2  {
    
    
    List<Producto> getAll();
    

    void addProducto(String stock, String nombre, String codigo, Double precio, categoriaProducto categoriaproducto);

    void addProducto(Producto producto);

   

   
}

ProductoServicioImplement.java

package com.example;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class ProductoServicioImplement implements ProductoServicio2{
    
    @Autowired
    ProductosRepository productosRepository;

    @Override
    public List<Producto> getAll() {
        return productosRepository.findAll();
    }

    @Override
    public void addProducto(String stock, String nombre, String codigo, Double precio , categoriaProducto categoriaproducto) {
        Producto p;
        p = new Producto(Integer.SIZE, stock, nombre, codigo, precio, categoriaproducto);
        productosRepository.save(p);

    }

    @Override
    public void addProducto(Producto producto) {
        productosRepository.save(producto);

    }

    
    public void updateProducto(Producto producto) {
        productosRepository.save(producto);

    }

  
    
    
    public Producto guardar(Producto producto) {
        return productosRepository.save(producto);
    }
    
    public boolean borrar(Producto producto) {
        try {
            productosRepository.delete(producto);
            return true;
        } catch(Exception ex) {
            return false;
        }
    }
    
    public Producto actualizar(Producto producto) {
        return productosRepository.save(producto);
    }
    
    
    
    public List<Producto>consultarTodos() {
        return productosRepository.findAll();
    }

    public Integer getProductoById(Producto producto) {
       
       return producto.getIdproducto();
    }
    
}

ProductosController.java

package com.example;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
    

//@RestController

@Controller
public class ProductosController {
   
    @Autowired
  private DataSource dataSource;
    @Autowired
    ProductoServicioImplement serviceProd;

  

    @GetMapping(path = "/Producto")
    public String ProductoForm(Model model){
        model.addAttribute("Producto", new Producto());
        return "Producto";
                
    }
    
    @PostMapping("/Producto")
    public String ProductoSubmit(@ModelAttribute Producto Producto,Model model){
        model.addAttribute("Producto",Producto);
        
        return "result";
        
        
    }

    
    
    @GetMapping (value = "/addProducto")
    public String addProduct (Model model) {
        model.addAttribute("producto", new Producto ());
        return "producto";

    }


     @PostMapping (value = "/addProducto")
    public String addProducto (Model model, String stock, String nombre, String codigo, Double precio, categoriaProducto categoriaproducto ) {
        serviceProd.addProducto(stock, nombre, codigo, precio, categoriaproducto);
        return "redirect:/list-productos";

    }

    @PostMapping (value = "/updateProducto")
    public String updateProducto (Model model, Producto producto) {
        serviceProd.updateProducto(producto);
        return "redirect:/list-productos";

    }

   
      @RequestMapping("/")
        String index() {
         return "index";
  }

  @RequestMapping("/db")
  String db(Map<String, Object> model) {
    try (Connection connection = dataSource.getConnection()) {
      Statement stmt = connection.createStatement();
      stmt.executeUpdate("CREATE TABLE IF NOT EXISTS ticks (tick timestamp)");
      stmt.executeUpdate("INSERT INTO ticks VALUES (now())");
      ResultSet rs = stmt.executeQuery("SELECT tick FROM ticks");

      ArrayList<String> output = new ArrayList<String>();
      while (rs.next()) {
        output.add("Read from DB: " + rs.getTimestamp("tick"));
      }

      model.put("records", output);
      return "db";
    } catch (Exception e) {
      model.put("message", e.getMessage());
      return "error";
    }
  }
 
}

ProductosRepository.java

package com.example;

import java.util.List;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface ProductosRepository extends MongoRepository<Producto, String> {
  
     
    List<Producto> getAll();

    Producto getProductoById(Integer idproducto);

    void addProducto(String stock, String nombre, String codigo, Double precio, categoriaProducto categoriaproducto);

    void addProducto(Producto producto);

    void updateProducto(Producto producto);

    void deleteProducto(Integer idproducto);
    
}

SimpleMongoConfig.java

package com.example;

import com.mongodb.ConnectionString;
import com.mongodb.MongoClientSettings;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.MongoTemplate;

@Configuration
public class SimpleMongoConfig {
 
    @Bean
    public MongoClient mongo() {


        ConnectionString connectionString = new ConnectionString("mongodb+srv://coteAdmin_:***password***@cluster0.wamjx.mongodb.net/test?retryWrites=true&w=majority");
        MongoClientSettings settings = MongoClientSettings.builder()
        .applyConnectionString(connectionString)
        .build();
        MongoClient mongoClient = MongoClients.create(settings);
        
        return MongoClients.create(settings);
    }

    @Bean
    public MongoTemplate mongoTemplate() throws Exception {
        return new MongoTemplate(mongo(), "test");
    }
}

Upvotes: 2

Views: 2221

Answers (1)

Jesper
Jesper

Reputation: 206816

The error is in your Spring Data JPA repository interface ProductosRepository, specifically this method:

Producto getProductoById(Integer idproducto);

Spring Data JPA is going to interpret the method name and generate a query for this. Since you've used the name Id in the method name, it's going to generate a query that's looking for the field named id. *

But your class Producto has a field named idproducto, not a field named id. You should change the method name in the repository interface to match the field name:

Producto getProductoByIdproducto(Integer idproducto);

Alternative solution: Rename the field idproducto in class Producto to id, including the corresponding getter and setter method.

*: Note that that matches what the error message is telling you:

Caused by: org.springframework.data.mapping.PropertyReferenceException: No property id found for type Producto!

It's looking for a field named id in class Producto, but it can't find such a field.

Upvotes: 3

Related Questions