Olá pessoal,
Hoje resolvi criar um “mini post” pra comentar bem rapidamente sobre o “Spring JDBC”. Basicamente, trata-se de um dos modulos do spring fwk que maximiza o tempo de codificação com a API JDBC, ou seja, promove a produtividade e principalmente a saúde mental dos programadores que precisam fazer sempre a mesma coisa: Criar conexão, Criar Statement, Executar operação e Fechar conexão ! 😦
Dando uma olhada na tabela abaixo, da pra notar que as tarefas mais enfadonhas, ficam a cargo do spring
Action | Spring | You |
---|---|---|
Define connection parameters. | X | |
Open the connection. | X | |
Specify the SQL statement. | X | |
Declare parameters and provide parameter values | X | |
Prepare and execute the statement. | X | |
Set up the loop to iterate through the results (if any). |
X | |
Do the work for each iteration. | X | |
Process any exception. | X | |
Handle transactions. | X | |
Close the connection, statement and resultset. | X |
O que você precisa ?
Do arquivo com as propriedades da conexão ( jdbc.properties )
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/livroonline
jdbc.username=root
jdbc.password=seupassword
Do arquivo com as informações dos beans ( ApplicationContext-DataAcess.xml )
<beans xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
De um bean que receba via injeção de dependencia o dataSource, para depois ser passado ao construtor do jdbcTemplate
package com.blogspot.jnatan.persistence.dao.impl;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import com.blogspot.jnatan.domainmodel.Autor;
import com.blogspot.jnatan.persistence.dao.IDAOAutor;
@Repository("DAOLivroJDBC")
public class DAOAutorJDBC implements IDAOAutor {
private JdbcTemplate jdbcTemplate;
@Autowired
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
public Collection findAll() {
Collection atores = this.jdbcTemplate.query( "select id_autor, nome, site from autor",
new RowMapper() {
public Autor mapRow(ResultSet rs, int rowNum) throws SQLException {
Autor autor = new Autor();
autor.setId( rs.getLong("id_autor") );
autor.setNome( rs.getString("nome"));
autor.setSite( rs.getString("site"));
return autor;
}
}
);
return atores;
}
public Autor findByPK(Long pk) {
String query = "select id_autor, nome, site from autor where id_autor = ?";
Autor autor = this.jdbcTemplate.queryForObject( query, new Long[]{ pk },
new RowMapper() {
public Autor mapRow(ResultSet rs, int rowNum)throws SQLException {
Autor autor = new Autor();
autor.setId( rs.getLong("id_autor") );
autor.setNome( rs.getString("nome") );
autor.setSite( rs.getString("site") );
return autor;
}
}
);
return autor;
}
public void remove(Autor entityType) {
this.jdbcTemplate.update( "delete from autor where id_autor = ?", entityType.getId() );
}
public void update(Autor entityType) {
this.jdbcTemplate.update( "update autor set nome = ? and site = ? where id_autor = ?", entityType.getNome(), entityType.getSite(), entityType.getId() );
}
public void insert(Autor entityType) {
this.jdbcTemplate.update( "insert into autor(id_autor, nome, site) values(?,?,?)", entityType.getId(), entityType.getNome(), entityType.getSite());
}
}
Como Funciona ?
Conclusão
As vantagens ficam bem claras em uma olhada rápida, é só imaginar o quanto de linhas de código JDBC foram suprimidas com o uso do spring, principalmente as que são relacionadas a tratamento de exceção.
Como foi dito no ínicio deste post, a real intenção desta parte do spring, é facilitar a codificação JDBC por parte do programador.
Links e Referencia
Abrcs.