<!-- https://mvnrepository.com/artifact/org.mariadb.jdbc/mariadb-java-client -->
<dependency>
<groupId>org.mariadb.jdbc</groupId>
<artifactId>mariadb-java-client</artifactId>
<version>2.7.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
${org.springframework-version}
은 위쪽에서 가져온다.
pom.xml 입력 후, 설치 완료시
3가지 항목이 정상적으로 설치되었는지 확인하면 된다.
root-context.xml
에서 공유 데이터 bean 설정을 해주어야 한다.
공유 데이터와 관련된 내용은 내가 예전에 적었던 글을 참조하자.
아래 링크를 따라가면 된다.
Spring 강의노트 : [Spring] 005 강의노트
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- Root Context: defines shared resources visible to all other web components -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.mariadb.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/sample" />
<property name="username" value="root" />
<property name="password" value="!123456" />
</bean>
</beans>
그렇다면 Controller에서는 어떻게 매칭을 해줄까?
package com.exam.controller;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Locale;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* Handles requests for the application home page.
*/
@Controller
public class HomeController {
// @Autowired : 자동 검색에서 매칭해줘
@Autowired
private DataSource dataSource;
@RequestMapping(value = "/index.do")
public String home(Locale locale, Model model) {
System.out.println("dataSource : " + dataSource);
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = this.dataSource.getConnection();
String sql = "SELECT now() as now ";
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
if(rs.next()) {
System.out.println("시간 출력 : " + rs.getString("now"));
}
} catch(SQLException e) {
System.out.println("[Error] " + e.getMessage());
} finally {
if(rs != null) try {rs.close();} catch(SQLException e) {}
if(pstmt != null) try {pstmt.close();} catch(SQLException e) {}
if(conn != null) try {conn.close();} catch(SQLException e) {}
}
return "home";
}
}
DataSource 객체를 생성하고 변수명은 반드시 root-context.xml
에서 설정한 bean id 값으로 입력해야 한다.
@Autowired
를 사용하면 Spring에서 자동 검색하여 공유 데이터
를 매칭해준다.
이제 index.do 를 브라우저 주소창에 입력해보자.
dataSource : org.springframework.jdbc.datasource.DriverManagerDataSource@298ec76b
시간 출력 : 2022-07-08 12:44:34.0
servlet-context.xml
에 component-scan 패키지 추가하기.<context:component-scan base-package="com.exam.model" />
@Autowired
private ExampleDAO dao;
@Autowired
private DataSource dataSource;
public void viewDataSource() {
System.out.println("dataSource : " + dataSource);
}
package com.exam.controller;
import java.util.Locale;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.exam.model.ExampleDAO;
@Controller
public class HomeController {
// @Autowired : 자동 검색에서 매칭해줘
@Autowired
private DataSource dataSource;
@Autowired
private ExampleDAO dao;
@RequestMapping(value = "/index.do")
public String home(Locale locale, Model model) {
System.out.println("dataSource : " + dataSource);
System.out.println("dao : " + dao);
dao.viewDataSource();
return "home";
}
}
7월 08, 2022 2:21:23 오후 org.apache.coyote.AbstractProtocol start
INFO: 프로토콜 핸들러 ["http-nio-80"]을(를) 시작합니다.
7월 08, 2022 2:21:23 오후 org.apache.catalina.startup.Catalina start
INFO: 서버가 [8096] 밀리초 내에 시작되었습니다.
dataSource : org.springframework.jdbc.datasource.DriverManagerDataSource@677f1a1f
dao : com.exam.model.ExampleDAO@1873eb5d
dataSource : org.springframework.jdbc.datasource.DriverManagerDataSource@677f1a1f
DriverManager, Connection, PrepareStatement, 데이터베이스 연결 해제 들을
JDBC Template가 대신 처리해, 사용한다.
사용자는 쿼리문 위주로만 작성할 수 있다. = 작업의 효율성?
<?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 https://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- Root Context: defines shared resources visible to all other web components -->
<!-- 1. dataSource -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.mariadb.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/sample" />
<property name="username" value="root" />
<property name="password" value="!123456" />
</bean>
<!-- 2. JDBC Template -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
dml
: update
select
: queryXXX