0

I am a beginner with Spring and I am working on a spring-boot project with Jooq.

I created an application properties which loads the database access settings, it's working, but I need a connection class that returns a connection object for me to use when needed.

It would be better if this class had a static getConnection method. I wrote the class as @Component and I put my @Value but all these attributes are null when I try to use them.

Is there another way to do this? Thank you so much.

@Component
public  class ConnectionFactory {
    @Value("${bws.codigo.escola}")
    static  private String codigoEscola;
    @Value("${bws.driver.connection}")
    static private String driver;
    @Value("${bws.database.name}")
    static private String nameDb;
    @Value("${bws.database.user}")
    static private String user;
    @Value("${bws.database.password}")
    static  private String password;
    @Value("${bws.database.server}")
    static private String server;
    @Value("${bws.string.connection}")
    static  private String firstUrlPart;
    @Value("${bws.string.connectionLast}")
    static  private String lastPartUrl;
    @Value("${bws.database.port}")
    static  private String port;

    static  String strConnection = firstUrlPart+server+":"+port+"/"+nameDb+lastPartUrl;
    public static Connection getConnection() throws SQLException {
        try {
            Class.forName(driver);
            return DriverManager.getConnection(strConnection,
                    user,password);
        } catch (ClassNotFoundException e) {
            throw new SQLException(e.getMessage());
        }
    }
}

that way I would use it in other classes

 try (Connection con = ConnectionFactory.getConnection()) {
     DSLContext ctx = DSL.using(con, SQLDialect.MYSQL);
     int count = ctx.selectCount()
                    .from(ALUNO)
                    .fetchOne(0, int.class);
     return count;
 }
Lukas Eder
  • 211,314
  • 129
  • 689
  • 1,509
Manzini
  • 117
  • 1
  • 10

1 Answers1

0

You could, of course, go ahead and inject all the values required to create a JDBC connection for each of your query on an ad-hoc basis. Or, much better, you inject a pre-configured DSLContext singleton instance that wraps the JDBC connection through a DataSource (ideally implemented by a connection pool).

The Spring Boot manual illustrates how this can be done: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-sql.html#boot-features-jooq

A more complete example can be seen here: https://github.com/jOOQ/jOOQ/tree/master/jOOQ-examples/jOOQ-spring-boot-example

The goal would be to have:

class SomeClass {
    @Autowired
    DSLContext ctx;

    public int countAluno() {
        return ctx.selectCount()
                  .from(ALUNO)
                  .fetchOne(0, int.class);
    }
}
Lukas Eder
  • 211,314
  • 129
  • 689
  • 1,509