Solucionado (ver solução)
Solucionado
(ver solução)
5
respostas

Springboot cria tabelas?

eu gostaria de saber se há um meio de criar as tabelas via spring boot. Afinal, até aqui, me parece, que usamos o jdbc puro. Mas em outros projetos, via configurações pela persistence.xml, a gente pode configurar o hibernate para criar as tabelas.

5 respostas
solução!

Tenta no application.properties a configuração

spring.jpa.hibernate.ddl-auto=update

só isso não basta. Tive uns erros. Vou mostrar como está aqui. MAIN:

@SpringBootApplication
public class ForIt{

   public static void main(String[] args)   {
      SpringApplication.run(ForIt.class, args);
   }

   @Bean
   public DataSource dataSource() {
       DriverManagerDataSource data = new DriverManagerDataSource();
       data.setDriverClassName("com.mysql.jdbc.Driver");
       data.setUrl("jdbc:mysql://localhost:3306/forit");
       data.setUsername("root");
       data.setPassword("root");
       return data;
   }

}

application.properties:

spring.jpa.hibernate.ddl-auto=update

Entidades. Abstrai os gets, sets e construtores:

@Entity
public class Address {

    @Id @GeneratedValue
    private int id;
    @NotNull 
    private String street;
    @NotNull 
    private String number;
    @NotNull 
    private String city;
@Entity
public class Job {

    @Id @GeneratedValue
    private int id;
    @NotNull
    private ExperienceLevel level;
    @NotNull
    private String programmingLanguage;
    @NotNull
    private double salary;
    private Address jobAdress;

controller:

@Controller
public class JobController {

    @Autowired
    private JobRepository jobRepository;

    @RequestMapping("/jobs")
    public String jobs(Model model) {
        Iterable<Job> jobs = this.jobRepository.findAll();
        model.addAttribute("jobs",jobs);

        return "jobs";
    }

AQUI TA O ERRO

2018-08-27 09:51:37.555  INFO 8868 --- [           main] br.com.jp.forIt.ForIt                    : Starting ForIt on vinicius-VPCEG17FB with PID 8868 (/home/vinicius/Documentos/forIt/target/classes started by vinicius in /home/vinicius/Documentos/forIt)
2018-08-27 09:51:37.560  INFO 8868 --- [           main] br.com.jp.forIt.ForIt                    : No active profile set, falling back to default profiles: default
2018-08-27 09:51:38.029  INFO 8868 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@28c4711c: startup date [Mon Aug 27 09:51:38 BRT 2018]; root of context hierarchy
2018-08-27 09:51:40.674  INFO 8868 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2018-08-27 09:51:40.701  INFO 8868 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
2018-08-27 09:51:40.702  INFO 8868 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.14
2018-08-27 09:51:40.944  INFO 8868 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2018-08-27 09:51:40.945  INFO 8868 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 2921 ms
2018-08-27 09:51:41.200  INFO 8868 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2018-08-27 09:51:41.206  INFO 8868 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-08-27 09:51:41.207  INFO 8868 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-08-27 09:51:41.207  INFO 8868 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-08-27 09:51:41.208  INFO 8868 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2018-08-27 09:51:41.283  INFO 8868 --- [           main] o.s.j.d.DriverManagerDataSource          : Loaded JDBC driver: com.mysql.jdbc.Driver
2018-08-27 09:51:41.973  INFO 8868 --- [           main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2018-08-27 09:51:42.003  INFO 8868 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
    name: default
    ...]
2018-08-27 09:51:42.128  INFO 8868 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate Core {5.0.12.Final}
2018-08-27 09:51:42.130  INFO 8868 --- [           main] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
2018-08-27 09:51:42.132  INFO 8868 --- [           main] org.hibernate.cfg.Environment            : HHH000021: Bytecode provider name : javassist
2018-08-27 09:51:42.188  INFO 8868 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2018-08-27 09:51:42.430  INFO 8868 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2018-08-27 09:51:42.690  WARN 8868 --- [           main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
2018-08-27 09:51:42.692  INFO 8868 --- [           main] o.apache.catalina.core.StandardService   : Stopping service Tomcat
2018-08-27 09:51:42.713  INFO 8868 --- [           main] utoConfigurationReportLoggingInitializer : 

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2018-08-27 09:51:42.721 ERROR 8868 --- [           main] o.s.boot.SpringApplication               : Application startup failed

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: I

https://www.baeldung.com/the-persistence-layer-with-spring-and-jpa

No passo 6 , acredito que a definição do DataSource deve ficar em uma classe com @Configuration , ou realizar toda a configuração no properties.

eu já resolvi. Fiz toda a configuração no properties e as tabelas foram criadas quando eu fiz o mapeamento @ManytoOne...

etc. obrigado