Spring (3) JDBC

Source: Internet
Author: User
Tags tutorialspoint

Step Description
1 Create a project with a name springexample and create a package Com.tutorialspoint under the src folder in the created project.
2 Add required spring libraries using Add External JARs option as explained in the spring Hello World example Chapter.
3 ADD Spring JDBC Specific latest libraries Mysql-connector-java.jar, Org.springframework.jdbc.jar and Org.springframework.transaction.jar in the project. You can download required libraries if you do not have them already.
4 Create DAO Interface Studentdao and list down all the required methods. Though It isn't required and can directly write studentjdbctemplate class, but as a good practice, let's do It.
5 Create Other required Java classes Student, studentmapper, studentjdbctemplate and Mainapp under the com.tutorialspoint package.
6 Make sure-already created Student table in TEST database. Also Make sure your MySQL server was working fine and you had read/write access on the database using the give username an d password.
7 Create Beans configuration file beans.xml under the src folder.
8 The final step is to create the content of all the Java files and Bean Configuration file and run the application as Expla Ined below.

The steps to integrate JDBC with spring are described below, and examples are given below

Following is the content of the Data Access Object interface file Studentdao.java:

Package Com.tutorialspoint;import Java.util.list;import Javax.sql.datasource;public interface Studentdao {/** * Thi S is the method to being used to initialize * database resources ie.    Connection.   */public void Setdatasource (DataSource ds);    /** * This is the method to being used to create * A record in the Student table.   */public void Create (String name, Integer age); /** * This is the method to being used to list down * A record from the Student table corresponding * to a passed s    Tudent ID.   */Public Student getstudent (Integer ID);    /** * This is the method to being used to list down * All the records from the Student table.   */Public list<student> liststudents (); /** * This is the method to being used to delete * A record from the Student table corresponding * to a passed stud    ENT ID.   */public void Delete (Integer ID);    /** * This was the method to being used to update * A record into the Student table. */PUblic void update (integer ID, integer age);} 

Following is the content of the student.java file:

Package Com.tutorialspoint;public class Student {   private Integer age;   private String name;   Private Integer ID;   public void Setage (Integer age) {      this.age = age;   }   Public Integer Getage () {      return age;   }   public void SetName (String name) {      this.name = name;   }   Public String GetName () {      return name;   }   public void SetId (Integer id) {      this.id = ID;   }   Public Integer getId () {      return ID;   }}

Following is the content of the studentmapper.java file

Package Com.tutorialspoint;import Java.sql.resultset;import Java.sql.sqlexception;import Org.springframework.jdbc.core.rowmapper;public class Studentmapper implements rowmapper<student> {public   Student Maprow (ResultSet rs, int rowNum) throws SQLException {      Student Student = new Student ();      Student.setid (Rs.getint ("id"));      Student.setname (rs.getstring ("name"));      Student.setage (Rs.getint ("Age"));      return student;}   }

Following is the implementation class file Studentjdbctemplate.java for the defined DAO interface Studentdao:

Package Com.tutorialspoint;import Java.util.list;import Javax.sql.datasource;import Org.springframework.jdbc.core.jdbctemplate;public class Studentjdbctemplate implements Studentdao {private   DataSource DataSource;      Private JdbcTemplate Jdbctemplateobject;      public void Setdatasource (DataSource DataSource) {this.datasource = DataSource;   This.jdbctemplateobject = new JdbcTemplate (DataSource);            public void Create (string name, Integer age) {string SQL = ' INSERT into Student (name, age) VALUES (?,?) ";      Jdbctemplateobject.update (SQL, name, age);      System.out.println ("Created Record name =" + name + "Age =" + age);   Return      } public Student getstudent (Integer id) {String SQL = ' select * from Student where id =? ';      Student Student = Jdbctemplateobject.queryforobject (SQL, New Object[]{id}, New Studentmapper ());   return student; } public list<student> liststudents () {String SQL = "Select * FROM Student ";      List <Student> students = jdbctemplateobject.query (SQL, New Studentmapper ());   return students;      } public void Delete (Integer id) {String SQL = ' Delete from Student where id =? ';      Jdbctemplateobject.update (SQL, id);      System.out.println ("Deleted Record with id =" + ID);   Return ' public void Update ' (integer ID, integer age) {String ' SQL = ' update Student set age =?      WHERE id =? ";      Jdbctemplateobject.update (SQL, age, id);      System.out.println ("Updated Record with id =" + ID);   Return }}

Following is the content of the mainapp.java file:

Package Com.tutorialspoint;import Java.util.list;import Org.springframework.context.applicationcontext;import Org.springframework.context.support.classpathxmlapplicationcontext;import Com.tutorialspoint.studentjdbctemplate;public class Mainapp {public static void main (string[] args) {Applicationc      Ontext context = new Classpathxmlapplicationcontext ("Beans.xml");            Studentjdbctemplate studentjdbctemplate = (studentjdbctemplate) context.getbean ("Studentjdbctemplate");      SYSTEM.OUT.PRINTLN ("------Records Creation--------");      Studentjdbctemplate.create ("Zara", 11);      Studentjdbctemplate.create ("Nuha", 2);      Studentjdbctemplate.create ("Ayan", 15);      SYSTEM.OUT.PRINTLN ("------Listing multiple Records--------");      list<student> students = studentjdbctemplate.liststudents ();         for (Student record:students) {System.out.print ("ID:" + Record.getid ());         System.out.print (", Name:" + record.getname ()); SyStem.out.println (", Age:" + record.getage ());      } System.out.println ("----Updating Record with ID = 2-----");      Studentjdbctemplate.update (2, 20);      SYSTEM.OUT.PRINTLN ("----Listing Record with ID = 2-----");      Student Student = studentjdbctemplate.getstudent (2);      System.out.print ("ID:" + Student.getid ());      System.out.print (", Name:" + student.getname ());     System.out.println (", Age:" + student.getage ()); }}

Following is the configuration file beans.xml:

<?xml version= "1.0" encoding= "UTF-8"? ><beans 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-3.0.xsd "> <!--initialization for data source--<bean id= "DataSource" class= "Org.springframework.jdbc.datasource.DriverManagerDataSource" > <pro Perty name= "Driverclassname" value= "Com.mysql.jdbc.Driver"/> <property name= "url" value= "jdbc:mysql:// Localhost:3306/test "/> <property name=" username "value=" root "/> <property name=" password "value=" pas Sword "/> </bean><!--Definition for studentjdbctemplate bean--<bean id= "studentjdbctemplate" class= "Com.tutorialspoint . Studentjdbctemplate "> <property name=" dataSource "ref=" DataSource "/> </bean> &LT;/BEANS&G T

The main part of this is the Red Font callout section.

In addition, the table that implements the code in the article is

create TABLE student (
   id   INT not NULL auto_increment,
   NAME Varchar (20) not null
   age  INT not null,
   PRIMARY KEY (id

< Span class= "pun" >< Span class= "pun" >< Span class= "pun" > article code from:

Http://www.tutorialspoint.com/spring/spring_jdbc_example.htm

Spring (3) JDBC

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.