Spring Tutorial – Connecting database using spring framework

Connecting database using spring framework

Spring Tutorial – Connecting database using spring framework

개요:

The Spring JDBC 템플릿은 널리 사용되는 데이터베이스 프로그램과 Java 호출 또는 요청을 통합하기 위해 JDBC ODBC 드라이버보다 더 나은 방법을 제공합니다.,,en,접근 방식이 크게 다릅니다,,en,후자의 경우,,en,개발자는 연결 및 쿼리 실행을 열고 닫는 것과 같은 많은 오버헤드에 대해 걱정해야 합니다.,,en,그러나 Sprint JDBC 템플릿을 사용하면 개발자가 핵심 작업에 집중할 수 있습니다.,,en,일반적인 JDBC 액세스의 문제점은 무엇입니까?,,en,JDBC는 4개의 드라이버를 통해 데이터베이스 프로그램에 대한 액세스를 제공합니다.,,en,각 드라이버에는 아래에 설명된 고유한 단점이 있습니다.,,en,JDBC-ODBC 브리지,,en,데이터베이스에 사용할 수 있는 Java 드라이버가 없을 때 사용됩니다.,,en,드라이버는 JDBC 호출을 ODBC 호출 또는 요청으로 변환한 다음 데이터베이스로 라우팅됩니다.,,en. While the objective of both Spring JDBC and JDBC and ODBC is the same, the approaches vary greatly. In case of the latter, the developer needs to worry about a lot of overheads such as opening and closing connections and query execution. But Sprint JDBC template allows the developer to focus on the core task of integration.

What are the Pain points of normal JDBC access?

JDBC provides access to database programs through four drivers. Each driver has its own disadvantages which are explained below.








JDBC-ODBC Bridge

  • This is used when there is no Java driver available for a database. The driver converts JDBC calls into ODBC calls or requests which then get routed to the database. JDBC 호출이 먼저 JDBC-ODBC 브리지를 통해 ODBC 드라이버로 이동해야 하므로 성능 오버헤드가 발생합니다.,,en,ODBC 드라이버는 클라이언트 시스템에 설치해야 하며 데이터베이스에 사용할 수 있는 Java 드라이버가 없기 때문에,,en,클라이언트 측 소프트웨어는 애플릿에 적합하지 않을 수 있습니다.,,en,네이티브 API 드라이버,,en,이 드라이버는 JDBC 요청을 데이터베이스가 이해하는 데이터베이스 API의 기본 요청으로 변환합니다.,,en,드라이버는 클라이언트 측 라이브러리를 사용합니다.,,en,데이터베이스에 JDBC 호출을 보내려면,,en,클라이언트 라이브러리는 클라이언트 시스템에 설치해야 합니다.,,en,여러가지 이유로,,en,드라이버는 인터넷을 통해 사용할 수 없습니다,,en,데이터베이스가 라이브러리에 대한 액세스를 거부하는 경우 드라이버가 중복될 수 있습니다.,,en,네트워크 프로토콜 드라이버,,en.
  • The ODBC driver needs to be installed on the client machine and since there is no Java driver available for the database, the client-side software might not be suitable for applets.

Native-API Driver

  • This driver converts JDBC requests into native requests of the database API which the database understands. The driver uses the client-side libraries. To send JDBC calls to the database, the client library needs to be installed into the client machine. Due to various reasons, the driver cannot be used over the Internet.
  • The driver might be redundant if the database declines access to its library.

Network-Protocol Driver

  • 이 드라이버는 중간 계층 또는 응용 프로그램 서버를 사용하여 통합하기 때문에,,en,데이터베이스 프로그램 호출,,en,중간 계층에서 코딩하려면 노력이 필요합니다.,,en,중간 계층을 추가하는 데 시간이 많이 걸릴 수 있습니다.,,en,Java 요청을 데이터베이스 프로그램과 통합하려면,,en,Native-Protocol 드라이버는 JDBC 호출을 공급업체별 데이터베이스 호출로 직접 변환하기 때문에 최상의 옵션으로 보입니다.,,en,Spring JDBC 접근 방식은 무엇입니까,,en,JDBC 드라이버에는 몇 가지 문제가 있습니다.,,en,위의 설명에서 볼 수 있듯이,,en,JDBC 드라이버는 JDBC-ODBC 브리지와 같은 외부 엔터티에 종속됩니다.,,en,미들웨어 및 데이터베이스 클라이언트 라이브러리,,en,이러한 엔터티를 사용할 수 없는 경우 문제가 발생할 수 있습니다.,,en,JDBC 드라이버로 작업할 때,,en,코딩을 많이 해야 할 수도 있습니다,,en JDBC calls to database programs, there is an effort required to code on the middle tier.
  • Adding the middle tier may be time-consuming.

Note: To integrate Java requests with database programs, the Native-Protocol driver appears to be the best option because it converts JDBC calls directly into vendor-specific database calls.

Must Read – Build your application using AngularJS and Spring data JPA?








What are the Spring JDBC approaches?

There are a few problems with the JDBC drivers, as can be seen in the descriptions above. JDBC drivers depend on external entities such as JDBC-ODBC bridge, middleware and database client libraries. Problems can arise in the event of unavailability of these entities. When you work with JDBC drivers, you may also need to code a lot. Too much dependence on other entities make accessing database programs a time consuming process. How is Spring JDBC different?

To solve the problem of integrating 자바 requests with database programs, Spring JDBC takes the following approaches:

JDBC Template class

This is a support class that comprises many methods which perform different tasks. For example, public int update method can insert, update or delete records and the public void execute method can execute DDL query. The availability of readymade methods gets tasks done easily.

NamedParameter

This capability is used to insert data by named parameter. To use this, the user needs to remember the data for the column.

SimpleJdbcTemplate

This wraps up the JDBC Template class and allows the user to pass arguments to access the database.

To summarise, Spring JDBC simplifies the integration of Java calls with databases with readymade methods and parameters and taking care of all low-level details that make JDBC API hard to work with.

Must Read – Steps to learn Spring Batch Service

What is Spring JDBC template?

The Spring JDBC template is a powerful way to integrate Java calls with database programs. While there are other ways such as the JDBC and ODBC combination to connect Java calls with databases, Spring JDBC lets the developer focus on the integration and response part while taking care of other low-level activities such as process exception, transaction handling, opening and closing connections, executing statements, setting up loops to iterate through results and close statement and result set.

What are the advantages of Spring JDBC template?

The main advantage of Spring JDBC template is it makes connecting with database programs a simpler and hassle-free experience for the developer. With other programs such as the JDBC drivers, the developer needs to work on other overheads such as coding on middle tier, fulfilling dependency between Java calls and libraries and database APIs and so on. The Spring JDBC Template takes away a lot of such tasks. Following are some of the important tasks managed by Spring JDBC template.

  • Opening the connection
  • Preparing and executing statement
  • Setting up loop for iterating through results
  • Exception processing
  • Handling transactions
  • Closing connections

Must Read – Steps to schedule tasks using Spring framework

Environment setup:

Setting up the environment for Spring based application development involves just three major steps.

  • Setting up Java Development Kit

다운로드 JDK from the Oracle site and then, 설치하고 구성. Then the PATH and JAVA_HOME environment variables must be set.

  • Setting of Eclipse IDE

Eclipse can be downloaded from the official website. Once downloaded, unpack the binaries and then set the PATH as well.

  • Setting up Spring libraries

The Spring libraries may be obtained from http://repo.spring.io/release/org/springframework/spring/. Again, it is important to set the CLASSPATH correctly.

Now your environment is ready to start developing Spring with Java applications.








Sample application:

In this section we will code some example programs to understand how Spring JDBC template works with databases

We will create a student object and insert the data in a database. We will also check the inserted data.

Listing 1: This is the student object

package com.techalpine.demo;

공공의 클래스 Student {

개인 String sname;

개인 String semail;

공공의 String getSname() {

return sname;

}

공공의 무효 setSname(String sname) {

this.sname = sname;

}

공공의 String getSemail() {

return semail;

}

공공의 무효 setSemail(String semail) {

this.semail = semail;

}

@ 재정의

공공의 String toString() {

return “Student [name is =” + sname + “, email is =” + semail + “]”;

}

}

Following is the DAO class to insert student data in a MySQL database. And also fetch data from the DB.

Listing 2: This is the student DAO object

package com.techalpine.demo;

수입 java.util.List;

수입 org.springframework.jdbc.core.JdbcTemplate;

공공의 클래스 StudentDao {

개인 JdbcTemplate jdbctemplate;

공공의 JdbcTemplate getJdbcTemplate() {

return jdbctemplate;

}

공공의 무효 setJdbcTemplate(JdbcTemplate jdbctemplate) {

this.jdbctemplate = jdbctemplate;

}

공공의 무효 insert(Student student){

String sqlinsert =”INSERT INTO STUDENT (NAME, EMAIL) VALUES(?,?);”;

String sname = student.getSname();

String semail = student.getSemail();

getJdbcTemplate().update(sqlinsert,새로운 Object[]{sname,semail});

}

공공의 List<Student> selectAll(){

String selectAllSql = “SELECT * FROM STUDENT;”;

return getJdbcTemplate().query(selectAllSql, 새로운 StudentRowMapper());

}

}

Following is the service class to access student data.

Listing 3: This is the student service class

package com. techalpine.demo;

수입 java.util.List;

공공의 클래스 StudentService {

개인 학생다오 학생다오,,en,StudentDao getStudentDao,,en,setStudentDao,,en,학생다오 = 학생다오,,en,학생 추가,,en,getStudentDao,,en,fetchAllStudents,,en,다음은 결과 집합 데이터를 해당 열과 일치시키는 행 매퍼 클래스입니다.,,en,이것은 행 매퍼 클래스입니다.,,en,학생 지도행,,en,결과 집합 결과 집합,,en,행 번호,,en,학생 학생 =,,en,학생.setSname,,en,결과 집합.getString,,en,학생.set메일,,en,다음은 Spring JDBC 템플릿과 설정을 사용하여 DB에서 데이터를 삽입하고 가져오는 메인 클래스이다.,,en,org.springframework.context.support.ClassPathXmlApplicationContext,,en,TestSpringDB데모,,de,ClassPathXmlApplicationContext,,en,spring-config.xml,,en,학생 서비스 학생 서비스 =,,en,학생 서비스,,en,nick@gmail.com,,en,학생 서비스.add학생,,en,학생.getSname,,en,성공적으로 추가되었습니다,,en,학생 = 학생 서비스.fetchAllStudents,,en,학생 목록 =,,en,프로그램이 실행되면 다음 출력이 표시됩니다,,en,학생 닉이 성공적으로 추가되었습니다.,,en;

공공의 StudentDao getStudentDao() {

return studentDao;

}

공공의 무효 setStudentDao(학생다오 학생다오,,en,StudentDao getStudentDao,,en,setStudentDao,,en,학생다오 = 학생다오,,en,학생 추가,,en,getStudentDao,,en,fetchAllStudents,,en,다음은 결과 집합 데이터를 해당 열과 일치시키는 행 매퍼 클래스입니다.,,en,이것은 행 매퍼 클래스입니다.,,en,학생 지도행,,en,결과 집합 결과 집합,,en,행 번호,,en,학생 학생 =,,en,학생.setSname,,en,결과 집합.getString,,en,학생.set메일,,en,다음은 Spring JDBC 템플릿과 설정을 사용하여 DB에서 데이터를 삽입하고 가져오는 메인 클래스이다.,,en,org.springframework.context.support.ClassPathXmlApplicationContext,,en,TestSpringDB데모,,de,ClassPathXmlApplicationContext,,en,spring-config.xml,,en,학생 서비스 학생 서비스 =,,en,학생 서비스,,en,nick@gmail.com,,en,학생 서비스.add학생,,en,학생.getSname,,en,성공적으로 추가되었습니다,,en,학생 = 학생 서비스.fetchAllStudents,,en,학생 목록 =,,en,프로그램이 실행되면 다음 출력이 표시됩니다,,en,학생 닉이 성공적으로 추가되었습니다.,,en) {

this.studentDao = studentDao;

}

공공의 무효 addStudent(Student student) {

getStudentDao().insert(student);

}

공공의 List<Student> fetchAllStudents() {

return getStudentDao().selectAll();

}

}

Following is the row mapper class to match the result set data with the corresponding columns.

Listing 4: This is the Row mapper class

package com. techalpine.demo;

수입 java.sql.ResultSet;

수입 java.sql.SQLException;

수입 org.springframework.jdbc.core.RowMapper;

공공의 클래스 StudentRowMapper implements RowMapper<Student>{

@ 재정의

공공의 Student mapRow(ResultSet resultSet, INT rowNumber) throws SQLException {

Student student = 새로운 Student();

student.setSname(resultSet.getString(1));

student.setSemail(resultSet.getString(2));

return student;

}

}

Now, following is the main class to insert the data and fetch it from the DB by using spring JDBC template and configuration.

Listing 5: 이것은 메인 클래스

package com.techalpine.demo;

수입 java.util.List;

수입 org.springframework.context.ApplicationContext;

수입 org.springframework.context.support.ClassPathXmlApplicationContext;

공공의 클래스 TestSpringDBDemo {

공공의 정적 인 무효 주(끈[] 인수) {

ApplicationContext context = 새로운 ClassPathXmlApplicationContext(“spring-config.xml”);

StudentService studentService = (StudentService) context.getBean(“studentnService”);

Student student = 새로운 Student();

student.setSname(“Nick”);

student.setSemail(“nick@gmail.com”);

studentService.addStudent(student);

체계.밖으로.나서 println(“Student : ” + student.getSname() + ” added successfully”);

List<Student> students = studentService.fetchAllStudents();

체계.밖으로.나서 println(“List of students = ” + students);

}

}

Once the program is executed it will show the following output.

Student Nick added successfully

학생인 경우 나열 = 닉,,en,Spring JDBC 템플릿은 데이터베이스 프로그램에 연결할 때 JDBC 및 ODBC 조합보다 분명히 더 강력합니다.,,en,아마도 가장 매력적인 기능은 데이터베이스 프로그램과의 통합을 간단하게 만드는 것입니다.,,en,특정 작업을 수행해야 하는 메서드가 포함되어 있습니다.,,en,개발자는 시간과 노력을 절약,,en,Spring 비디오 튜토리얼 보기,,en








결론:

The Spring JDBC template is obviously more powerful than the JDBC and ODBC combination when it comes to connecting to database programs. Probably the most attractive feature is how simple it makes integration with database programs. It comes loaded with methods which are supposed to perform specific tasks. As a result, the developer saves time and effort.

Watch Spring Video tutorials

============================================= ============================================== 아마존에서 최고의 Techalpine 책을 구입하십시오,en,전기 기술자 CT 밤나무 전기,en
============================================== ---------------------------------------------------------------- electrician ct chestnutelectric
error

Enjoy this blog? Please spread the word :)

Follow by Email
LinkedIn
LinkedIn
Share