0

Estoy haciendo una API REST en spring framework y he empezado con usuarios.

Voy a dejar los ficheros que estan implicados por si localizais algun error que no alcanzo a ver, porque realmente no entiendo porque no funciona:

application.properties

spring.datasource.url=jdbc:mysql://localhost:3306/db_tienda?useSSL=false&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.database-platform=org.hibernate.dialect.MySQL57Dialect
spring.jpa.hibernate.ddl-auto=update
logging.level.org.hibernate.SQL=debug

server.port=8080

Entity

package com.crn.tienda.entity;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.springframework.data.annotation.Id;

/**
 * Cliente
 */
@Entity
public class Usuario implements Serializable{

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "nombre")
    private String nombre;

    @Column(name = "apellidos")
    private String apellidos;

    @Column(name = "usuario")
    private String usuario;

    @Column(name = "email")
    private String email;

    @Column(name = "passsword")
    private String passsword;

    @Column(name = "fecha_registro")
    @Temporal(TemporalType.DATE)
    private Date createAt;

    /**
     * @return Long return the id
     */
    public Long getId() {
        return id;
    }

    /**
     * @param id the id to set
     */
    public void setId(Long id) {
        this.id = id;
    }

    /**
     * @return String return the nombre
     */
    public String getNombre() {
        return nombre;
    }

    /**
     * @param nombre the nombre to set
     */
    public void setNombre(String nombre) {
        this.nombre = nombre;
    }

    /**
     * @return String return the apellidos
     */
    public String getApellidos() {
        return apellidos;
    }

    /**
     * @param apellidos the apellidos to set
     */
    public void setApellidos(String apellidos) {
        this.apellidos = apellidos;
    }

    /**
     * @return String return the usuario
     */
    public String getUsuario() {
        return usuario;
    }

    /**
     * @param usuario the usuario to set
     */
    public void setUsuario(String usuario) {
        this.usuario = usuario;
    }

    /**
     * @return String return the email
     */
    public String getEmail() {
        return email;
    }

    /**
     * @param email the email to set
     */
    public void setEmail(String email) {
        this.email = email;
    }

    /**
     * @return String return the passsword
     */
    public String getPasssword() {
        return passsword;
    }

    /**
     * @param passsword the passsword to set
     */
    public void setPasssword(String passsword) {
        this.passsword = passsword;
    }

    /**
     * @return Date return the createAt
     */
    public Date getCreateAt() {
        return createAt;
    }

    /**
     * @param createAt the createAt to set
     */
    public void setCreateAt(Date createAt) {
        this.createAt = createAt;
    }

}

DAO

    package com.crn.tienda.dao;

    import com.crn.tienda.entity.Usuario;

    import org.springframework.data.jpa.repository.Query;
    import org.springframework.data.repository.CrudRepository;

    /**
     * IUsuarioDao
     */
    public interface IUsuarioDao extends CrudRepository<Usuario,Long> {

        @Query("select u from Usuario u where u.email = ?1 and u.password = ?2")
        Usuario findByEmailandPassword(String email, String password);

        @Query("select u from Usuario u where u.usuario = ?1 and u.password = ?2")
        Usuario findByUserandPassword(String usuario, String password);

    }

Services (IUsuarioService)

package com.crn.tienda.services;

import java.util.List;

import com.crn.tienda.entity.Usuario;

/**
 * IUsuarioService
 */
public interface IUsuarioService {

    public List<Usuario> findAll();

}

Services (UsuarioServiceImpl)

package com.crn.tienda.services;

import java.util.List;

import com.crn.tienda.dao.IUsuarioDao;
import com.crn.tienda.entity.Usuario;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * UsuarioServiceImpl
 */
@Service
public class UsuarioServiceImpl implements IUsuarioService {

    @Autowired
    private IUsuarioDao usuarioDao;

    @Override
    @Transactional(readOnly = true)
    public List<Usuario> findAll() {
        return (List<Usuario>) usuarioDao.findAll();
    }

}

Controllers

package com.crn.tienda.controllers;

import java.util.List;

import com.crn.tienda.entity.Usuario;
import com.crn.tienda.services.IUsuarioService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * UsuarioRestController
 */
@RestController
@RequestMapping("/api")
public class UsuarioRestController {

    @Autowired
    private IUsuarioService usuarioService;

    @GetMapping("/usuarios")
    public List<Usuario> index() {
        return usuarioService.findAll();
    }


}

Entonces cuando accedo a mi url (http://localhost:8080/api/usuarios) me da un error:

Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing this as a fallback.
Mon May 27 23:08:36 CEST 2019
There was an unexpected error (type=Not Found, status=404).
No message available

Deberia de mandarme un JSON de todos los usuarios de la base de datos.

MI DER es el siguiente :

introducir la descripción de la imagen aquí

Hasta el momento no he logrado encontrar donde esta el error. A ver si me podeis echar una mano. Mil gracias.

El Log es el siguiente:

  .   ____          _            __ _ _

 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \

( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \

 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )

  '  |____| .__|_| |_|_| |_\__, | / / / /

 =========|_|==============|___/=/_/_/_/

 :: Spring Boot ::        (v2.1.5.RELEASE)



2019-05-27 23:21:02.356  INFO 9260 --- [  restartedMain] com.crn.tienda.demo.DemoApplication      : Starting DemoApplication on DESKTOP-REPNVGL with PID 9260 (C:\Users\Josel\Desktop\TIENDA-SPRING-ANGULAR\BACKEND\tienda\demo\target\classes started by Josel in C:\Users\Josel\Desktop\TIENDA-SPRING-ANGULAR\BACKEND\tienda\demo)

2019-05-27 23:21:02.362  INFO 9260 --- [  restartedMain] com.crn.tienda.demo.DemoApplication      : No active profile set, falling back to default profiles: default

2019-05-27 23:21:02.432  INFO 9260 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable

2019-05-27 23:21:02.432  INFO 9260 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'

2019-05-27 23:21:03.511  INFO 9260 --- [  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.

2019-05-27 23:21:03.542  INFO 9260 --- [  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 17ms. Found 0 repository interfaces.

2019-05-27 23:21:04.005  INFO 9260 --- [  restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$8fde8269] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)

2019-05-27 23:21:04.470  INFO 9260 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)

2019-05-27 23:21:04.499  INFO 9260 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]

2019-05-27 23:21:04.499  INFO 9260 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.19]

2019-05-27 23:21:04.634  INFO 9260 --- [  restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext

2019-05-27 23:21:04.634  INFO 9260 --- [  restartedMain] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 2202 ms

2019-05-27 23:21:04.894  INFO 9260 --- [  restartedMain] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...

2019-05-27 23:21:05.077  INFO 9260 --- [  restartedMain] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.

2019-05-27 23:21:05.126  INFO 9260 --- [  restartedMain] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [

    name: default

    ...]

2019-05-27 23:21:05.228  INFO 9260 --- [  restartedMain] org.hibernate.Version                    : HHH000412: Hibernate Core {5.3.10.Final}

2019-05-27 23:21:05.230  INFO 9260 --- [  restartedMain] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found

2019-05-27 23:21:05.405  INFO 9260 --- [  restartedMain] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.0.4.Final}

2019-05-27 23:21:05.564  INFO 9260 --- [  restartedMain] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL57Dialect

2019-05-27 23:21:05.838  INFO 9260 --- [  restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'

2019-05-27 23:21:05.859  INFO 9260 --- [  restartedMain] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729

2019-05-27 23:21:06.134  INFO 9260 --- [  restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'

2019-05-27 23:21:06.195  WARN 9260 --- [  restartedMain] aWebConfiguration$JpaWebMvcConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning

2019-05-27 23:21:06.506  INFO 9260 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''

2019-05-27 23:21:06.510  INFO 9260 --- [  restartedMain] com.crn.tienda.demo.DemoApplication      : Started DemoApplication in 4.594 seconds (JVM running for 5.149)
5
  • y que error te da? el 27 may. 2019 a las 21:19
  • esta puesto en la pregunta fijate encima de la image del DER.
    – josanangel
    el 27 may. 2019 a las 21:20
  • Puede que sea tema de los paquetes stackoverflow.com/questions/36819277/…
    – Angabo
    el 27 may. 2019 a las 21:35
  • eso he estado probando pero por ejemplo si el main esta en loquesea.main mis paquetes de controllers,entities,etc.. deben de ser loquesea.main.controllers...... pero no me funciona tampoco. Tambien lo he probado poniendo asi como en le ejemplo (con los puntos) o creandolo directamente dentro del directorio, pero en ambas no funcionan, de hecho ni compilan.
    – josanangel
    el 27 may. 2019 a las 22:08
  • ¿Puedes añadir a tu pregunta una captura donde se vea la estructura de paquetes, y que se vea dónde está el main y dónde los controladores? ¿Y puedes añadir también el código de la clase main con las anotaciones que tengas en ella?
    – kerten
    el 29 may. 2019 a las 9:54

0

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

Examina otras preguntas con la etiqueta o formula tu propia pregunta.