Help with Spring jdbcTemplate

Asked

Viewed 185 times

0

I created a class:

package com.market.config;

    import javax.activation.DataSource;

    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.jdbc.core.JdbcTemplate;
    import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
    import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;

    @Configuration
    public class BdConfig {

        @Bean
        public JdbcTemplate jdbcTemplate(DataSource dataSource) {
            return new JdbcTemplate(dataSource);
        }
    }

I’m with that error: inserir a descrição da imagem aqui

and I have doubts how to do a method to get this datasource set up in my application.properties:

spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/market
spring.datasource.username=root
spring.datasource.password=

1 answer

0

Hi,

You need to configure the datasource before

Thus

 @Configuration
    public class BdConfig {


        @Bean
        public DataSource getDataSource() {
            DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
            dataSourceBuilder.driverClassName("oracle.jdbc.driver.OracleDriver");
            dataSourceBuilder.url("jdbc://blablabla");
            dataSourceBuilder.username("usuario");
            dataSourceBuilder.password("senha");
            return dataSourceBuilder.build();
        }


        @Bean
        public JdbcTemplate jdbcTemplate(DataSource dataSource) {
            return new JdbcTemplate(dataSource);
        }
    }

Anyway depending on the spring data version you are using you do not need to configure jdbctemplate manually, just inject it into your Repository or service using autowired so

@Repository
public class MeuRepositorio {

    @Autowired
    JdbcTemplate jdbcTemplate;
  • I am using version 2. something I think is the most current, in case I only need to use @Autowired Jdbctemplate jdbcTemplate; in a DAO class without using datasource? you could give me an example how would this use in a dao ?

  • That, just do the '@Autowired', the ideal is that it was in a '@Repository', which is called by a '@Service', has an example of using Jdbctemplate using '@Autowired' here https://spring.io/guides/gs/relational-data-access/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.