Importante

Você está vendo a versão anterior da nova experiência da Alura que estamos preparando para você. Em breve, ela ganha uma identidade visual novinha totalmente pensada em potencializar seus estudos!

17
respostas

Tabelas nao criadas

Ola, li o forum de porem nao encontrei soluçao para minha duvida.. as minhas tabelas nao sao criadas no h1, vem só as padrao..

data source

spring.datasource.driverClassName=org.h2.Driver spring.datasource.url=jdbc:h2:mem:aluraforum spring.datasource.username=sa spring.datasource.password=

# jpa

spring.jpa.database-platform=org.hibernate.dialect.H2Dialect spring.jpa.hibernate.ddl-auto=update spring.jpa.defer-datasource-initialization=true

# h2

spring.h2.console.enabled=true spring.h2.console.path=/h2-consoles

PARTE DO CODIGO CLASSE USUARIO![Insira aqui a descrição dessa imagem para ajudar na acessibilidade](https://cdn1.gnarususercontent.com.br/1/772278/a4f783aa-ca98-418b-96d6-fa2d56d7f085.png) ![Insira aqui a descrição dessa imagem para ajudar na acessibilidade](https://cdn1.gnarususercontent.com.br/1/772278/efe8ba3d-2a1c-41a8-8ac1-ef0586878cce.png)   
import javax.persistence.Id;

import org.springframework.boot.autoconfigure.domain.EntityScan;

@Entity public class Usuario {

@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String nome;
private String email;
private String senha;

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((id == null) ? 0 : id.hashCode());
    return result;

    ![Insira aqui a descrição dessa imagem para ajudar na acessibilidade](https://cdn1.gnarususercontent.com.br/1/772278/32104a89-2a74-42d8-9b50-4f40eb838f88.png) ![Insira aqui a descrição dessa imagem para ajudar na acessibilidade](https://cdn1.gnarususercontent.com.br/1/772278/432006f8-e65a-4fd1-a83c-d702b9df8ce3.png)   
17 respostas

Opa Cristiano, tudo certo?

A partir da versão 2.5 do spring, você precisa adicionar uma propriedade no application.properties:

spring.jpa.defer-datasource-initialization=true

Para ele entender que deve ler o arquivo na hora de inicializar o projeto.

Segue o link da alteração.

Qualquer duvida pode mandar :)

engraçado, mesmo colocando a linha as tableas nao sao criadas..

. __ _ __ _ _ /\ / _'_ _ _ _()_ _ __ _ \ \ \ ( ( )___ | ' | '| | ' / ` | \ \ \ \/ ___)| |)| | | | | || (| | ) ) ) ) ' |__| .|| ||_| |_, | / / / / =========||==============|__/=//// :: Spring Boot :: (v2.5.1)

2021-06-21 19:05:47.919 INFO 14500 --- [ restartedMain] controller.DemoApplication : Starting DemoApplication using Java 11.0.11 on DESKTOP-DFR3272 with PID 14500 (C:\ForumDisculsao\demo\target\classes started by diony in C:\ForumDisculsao\demo) 2021-06-21 19:05:47.923 INFO 14500 --- [ restartedMain] controller.DemoApplication : No active profile set, falling back to default profiles: default 2021-06-21 19:05:48.016 INFO 14500 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable 2021-06-21 19:05:48.016 INFO 14500 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG' 2021-06-21 19:05:48.748 INFO 14500 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode. 2021-06-21 19:05:48.767 INFO 14500 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 7 ms. Found 0 JPA repository interfaces. 2021-06-21 19:05:49.745 INFO 14500 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http) 2021-06-21 19:05:49.759 INFO 14500 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat] 2021-06-21 19:05:49.760 INFO 14500 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.46] 2021-06-21 19:05:49.886 INFO 14500 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 2021-06-21 19:05:49.886 INFO 14500 --- [ restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1870 ms 2021-06-21 19:05:49.933 INFO 14500 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting... 2021-06-21 19:05:50.120 INFO 14500 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed. 2021-06-21 19:05:50.128 INFO 14500 --- [ restartedMain] o.s.b.a.h2.H2ConsoleAutoConfiguration : H2 console available at '/h2-consoles'. Database available at 'jdbc:h2:mem:aluraforum' 2021-06-21 19:05:50.337 INFO 14500 --- [ restartedMain] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default] 2021-06-21 19:05:50.397 INFO 14500 --- [ restartedMain] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.32.Final 2021-06-21 19:05:50.557 INFO 14500 --- [ restartedMain] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final} 2021-06-21 19:05:50.688 INFO 14500 --- [ restartedMain] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect 2021-06-21 19:05:50.994 INFO 14500 --- [ restartedMain] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform] 2021-06-21 19:05:51.005 INFO 14500 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default' 2021-06-21 19:05:51.073 WARN 14500 --- [ restartedMain] JpaBaseConfiguration$JpaWebConfiguration : 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 2021-06-21 19:05:51.517 INFO 14500 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729 2021-06-21 19:05:51.666 INFO 14500 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path '' 2021-06-21 19:05:51.690 INFO 14500 --- [ restartedMain] controller.DemoApplication : Started DemoApplication in 4.214 seconds (JVM running for 4.766) 2021-06-21 19:06:22.024 INFO 14500 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet' 2021-06-21 19:06:22.024 INFO 14500 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet' 2021-06-21 19:06:22.025 INFO 14500 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 1 ms

Opa Cristiano,

Você poderia me enviar seu projeto, caso você tenha github ou subir os arquivos em um drive e me mandar um link, para que eu consiga te ajudar melhor?

Provavelmente é por conta do pacote onde estao suas entidades JPA nao ser um pacote filho de onde esta localizada a classe main(ForumApplication).

Verifique isso tambem.

Fiz o procedimento adicionando o que precisa para o spring boot2.5 ou superior, porém apareceu esse erro.

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled. 2021-06-24 14:18:07.515 ERROR 15104 --- [ restartedMain] o.s.boot.SpringApplication : Application run failed

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'securityConfigurations': Unsatisfied dependency expressed through field 'tokenService'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'tokenService': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'forum.jwt.expiration' in value "${forum.jwt.expiration}" 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]

Opa Diogo,

Creio que você só tenha esquecido de adicionar no application.properties as configurações do jwt para poder popular esta chave:

# jwt
forum.jwt.secret=rm'!@N=Ke!~p8VTA2ZRK~nMDQX5Uvm!m'D&]{@Vr?G;2?XhbC:Qa#9#eMLN\}x3?JR3.2zr~v)gYF^8\:8>:XfB:Ww75N/emt9Yj[bQMNCWwW\J?N,nvH.<2\.r~w]*e~vgak)X"v8H`MH/7"2E`,^k@n<vE-wD3g9JWPy;CrY*.Kd2_D])=><D?YhBaSua5hW%{2]_FVXzb9`8FH^b[X3jzVER&:jw2<=c38=>L/zBq`}C6tT*cCSVC^c]-L}&/
forum.jwt.expiration=86400000

Essas informações eu coloquei no application.properties, mas parece que ele não esta fazendo a leitura.

Manda sua classe que chama o valor do properties como ficou por favor

package br.com.alura.forum.config.security;

import java.util.Date;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import br.com.alura.forum.modelo.Usuario;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

@Service
public class TokenService {

    @Value("${forum.jwt.expiration}")
    private String expiration;

    // a anotação @Value injeta as propriedades do arquivo application.properties
    // como o token e o tempo de expiração

    @Value("${forum.jwt.secret}")
    private String secret;

    public String geraToken(Authentication authentication) {
        Usuario logado = (Usuario) authentication.getPrincipal();
        Date hoje = new Date();
        Date dataExpericao = new Date(hoje.getTime() + Long.parseLong(expiration));

        return Jwts.builder()
                .setIssuer("API do Forum da Alura")
                .setSubject(logado.getId().toString())
                .setIssuedAt(hoje)
                .setExpiration(dataExpericao)
                .signWith(SignatureAlgorithm.HS256, secret)
                .compact();
    }

    public boolean isTokenValido(String token) {
        try {
            Jwts.parser().setSigningKey(this.secret).parseClaimsJws(token);
            return true;
        } catch (Exception e) {
            return false;
        }

    }

    public Long getIdUsuario(String token) {
        Claims claims = Jwts.parser().setSigningKey(this.secret).parseClaimsJws(token).getBody();
        return Long.parseLong(claims.getSubject());
    }
}

Opa Diogo, seu projeto esta no git? ou em um drive?

Pode ser algo relacionado a estrutura de pastas ou ao application.properties...

Gostaria de confirmar melhor

https://1drv.ms/u/s!AsyoxikbnWtBjCNHebkRTdvJsvCa?e=xvZhrl

https://1drv.ms/u/s!AsyoxikbnWtBjkZmGnVontKTHQox?e=mloyKk

tem esses dois links, o primeiro com a pasta completa e o segundo o arquivo .jar

Oi Diogo,

Tem um problema no seu arquivo data.sql:

INSERT INTO USUARIO(id, nome) VALUES(1, 'ROLE_ALUNO');
INSERT INTO USUARIO(id, nome) VALUES(2, 'ROLE_MODERADOR');

Mas deveria ser:

INSERT INTO PERFIL(id, nome) VALUES(1, 'ROLE_ALUNO');
INSERT INTO PERFIL(id, nome) VALUES(2, 'ROLE_MODERADOR');

Atualizei as informações que vc passou e continua com esse erro, o erro na tag do pom.xml continua tambem. Mudei a versão do spring boot para o 2.4.8, o erro continua.

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'tokenService': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'forum.jwt.expiration' in value "${forum.jwt.expiration}" at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:405) ~[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]

Diogo,

Eu baixei o seu projeto e o rodei com profile prod e funcionou normalmente aqui.

Como você fez para rodar o projeto? profile prod? me passa as etapas para fazer aqui

Seu projeto ja esta utilizando profiles, pois tem as classe DevSecurityConfigurations e SecurityConfigurations.

Veja no terceiro curso de Spring Boot, na aula de profiles, como configurar no eclipse o profile sendo executado no momento: https://cursos.alura.com.br/course/spring-boot-profiles-testes-deploy/task/81098

Entendo, vou fazer essa parte de profiles e usar outro banco para ver o projeto rodando, talvez seja esse no h2 ou em sua versão também