What is Spring – JDBC Framework?

Spring JDBC

Spring Series: Aprende a integración de JDBC por exemplo,,en,Neste artigo imos discutir sobre a característica de JDBC proporcionada polo marco Spring,,en,Esta guía axudará aos desenvolvedores a seguir os pasos e implementar o JDBC usando o framework Spring,,en,Fundamentos DAO,,en,DAO significa obxecto de acceso a datos que se usa habitualmente para a interacción da base de datos. Existen os ODS para proporcionar un medio para ler e escribir datos na base de datos e deberían expoñer esta funcionalidade a través dunha interface coa que o resto da aplicación accederá a eles,,en,Spring JBDC,,en,Spring ten o seu propio cadro de JDBC que nos axuda a limpar o código JDBC ao asumir a carga de xestión de recursos e manexo de erros,,en,Isto permítelle concentrarse nas declaracións e consultas para obter os seus datos desde e para a base de datos,,en

Visión global

In this article we will discuss about the JDBC feature provided by the Spring framework. We will be concentrating more on the implementation and configuration part. This guide will help the developers to follow the steps and implement JDBC using Spring framework.

DAO Basics

DAO stands for data access object which is commonly used for database interaction.DAOs exist to provide a means to read and write data to the database and they should expose this functionality through an interface by which the rest of the application will access them.







Spring JBDC

Spring has its own JDBC framework which helps us to clean up JDBC code by shouldering the burden of resource management and error handling. This leaves you free to concentrate on the statements and queries to get your data to and from the database.

Os cadros de acceso a datos de Spring incorporan unha clase de modelo coñecida como JdbcTemplate,,en,Un JdbcTemplate só precisa do Datasource para comezar a traballar,,en,O seguinte fragmento de código mostra a creación de JdbcTemplate,,en,JdbcTemplate template = novo JdbcTemplate,,en,myDataSource,,en,O seguinte fragmento de código mostra o cableado de feixóns DAO con JdbcTemplate,,en,jdbcTemplate,,en,alumnoDao,,en,StudentDaoJdbc,,en,cursoDao,,en,CursoDaoJdbc,,en,A continuación móstrase un exemplo de acceso á base de datos usando o modelo JDBC de primavera,,en,O primeiro compoñente é unha interface,,en,StudentDAO,,en,para definir o método a implementar,,en,Aquí o método é inserir os detalles do alumno,,en,paquete com.techalpine.dao,,pt,interface público StudentDAO,,en,public void insertStudent,,en,O seguinte compoñente é a clase de implementación da interface anteriormente mencionada,,en,StudentDAOImpl,,en,Implementa o método de inserción mediante o modelo JDBC,,en. A JdbcTemplate only needs Datasource to start working.

Following code snippet shows the creation of JdbcTemplate.

JdbcTemplate template = new JdbcTemplate(myDataSource);

Following code snippet shows the wiring of DAO beans with JdbcTemplate.

<bean id =”jdbcTemplate”

class =”org.springframework.jdbc.core.JdbcTemplate”>

<property name=”dataSource”><ref bean=”dataSource”/></propiedade>

</feixón>

<bean id =”studentDao” class =”StudentDaoJdbc”>

<property name=”jdbcTemplate”><ref bean=”jdbcTemplate”/></propiedade>

</feixón>

<bean id =”courseDao” class =”CourseDaoJdbc”>

<property name=”jdbcTemplate”><ref bean=”jdbcTemplate”/></propiedade>

</feixón>







Following is an example of accessing the database using spring JDBC template.

  • The first component is an interface (StudentDAO) to define the method to be implemented. Here the method is to insert the student details.

package com.techalpine.dao;

public interface StudentDAO {

public void insertStudent(Corda, Corda);

}

  • The next component is the implementation class of the above mentioned interface (StudentDAOImpl). It implements the insert method by using JDBC template.

package com.techalpine.dao;

importar java.sql.ResultSet,,en,importación java.sql.SQLException,,en,importar javax.sql.DataSource,,en,importación org.springframework.jdbc.core.JdbcTemplate,,en,import org.springframework.jdbc.core.RowMapper,,en,A clase pública StudentDAOImpl implementa StudentDAO,,en,privado JdbcTemplate jdbcTemplate,,en,public void setDataSource,,en,DataSource dataSource,,en,this.jdbcTemplate = new JdbcTemplate,,en,Especifique consulta SQL para inserir,,en,Consulta de cadea =,,en,INSERTA EN ESTUDANTE,,en,VALORES,,en,Especifique o método a chamar,,en,novo obxecto,,en,O terceiro compoñente é o ficheiro de configuración,,en,para definir a fonte de datos e fiación dos faba,,en,www.springframework.org/schema/beans http,,en,www.springframework.org/schema/beans/spring-beans.xsd,,en,destruír o método =,,en,org.apache.commons.dbcp.BasicDataSource,,en,driverClassName,,en,org.hsqldb.jdbcDriver,,en,hsqldb,,en,hsql,,en,techalpina,,en,alumnoDAO,,en,com.techalpine.dao.StudentDAOImpl,,pt,Agora a parte final é unha clase java autónoma,,en,para probar a mostra,,en;

import java.sql.SQLException;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;

import org.springframework.jdbc.core.RowMapper;

public class StudentDAOImpl implements StudentDAO {

private JdbcTemplate jdbcTemplate;

public void setDataSource(DataSource dataSource) {

this.jdbcTemplate = new JdbcTemplate(dataSource);

}

public void insertStudent(String name, String address) {

// Specify SQL query for insert

String query = “INSERT INTO STUDENT (nome,address) VALUES (?,?)”;

// Specify the method to be called

jdbcTemplate.update(pregunta, new Object[] );

}

}

  • The third component is the configuration file (xml) to define the data source and wiring the beans.

<?xml version=”1.0″ encoding=”UTF-8″?>

<feixón xmlns =”http://www.springframework.org/schema/beans”

xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”xsi:schemaLocation=”http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd”>

<bean id =”dataSource” destroy-method=”close” class =”org.apache.commons.dbcp.BasicDataSource”>

<property name=”driverClassName” value=”org.hsqldb.jdbcDriver”/>

<property name=”url” value=”JDBC:hsqldb:hsql://localhost”/>

<property name=”username” value=”techalpine”/>

<property name=”password” value=”techalpine”/>

</feixón>

<bean id =”studentDAO” class =”com.techalpine.dao.StudentDAOImpl”>

<property name=”dataSource” ref=”dataSource”/>

</feixón>

</feixóns>

  • Now the final part is a standalone java class (java) to test the sample. A clase principal recupera o feixón do contenedor de primavera e despois chama ao método de inserción para inserir os datos do alumno,,en,clase pública Estudante,,en,ApplicationContext context = novo ClassPathXmlApplicationContext,,en,student.xml,,en,StudentDAO studentDAO =,,en,studentDAO.insertStudent,,en,o que,,hu,Delhi,,en,Este artigo é para os desenvolvedores que queren saltar á codificación sen perder moito tempo na parte teórica,,en,Tentamos manter a parte teórica mínima e explicar máis sobre a codificación e configuración,,en,Espero que isto axude á comunidade dos desenvolvedores,,en.

package com.techalpine.dao;

importación org.springframework.context.ApplicationContext;

importación org.springframework.context.support.ClassPathXmlApplicationContext;

public class Student {

public static void main(Corda[] args) {

ApplicationContext context = new ClassPathXmlApplicationContext(“student.xml”);

StudentDAO studentDAO = (StudentDAO) context.getBean(“studentDAO”);

studentDAO.insertStudent(“Amit”,”Delhi”);

}

}









Conclusión

This article is for the developers who wants to jump into coding without wasting much time on the theoretical part. We have tried to keep the theoretical part minimum and explain more on the coding and configuration. Hope this will help the developers’ community.

============================================= ============================================== Buy best TechAlpine Books on Amazon
============================================== ---------------------------------------------------------------- electrician ct chestnutelectric
error

Enjoy this blog? Please spread the word :)

Follow by Email
LinkedIn
LinkedIn
Share