★ 결과
실제 서비스에서 많이 쓰는 쿼리문들로 구성해놓은 틀을 공개합니다! ^.^//
My-sql과 연동 및 유지보수를 위해 'Hikari-CP', 'MyBatis', Lombok'을 이용하였습니다.
★ 사전설정
개발환경: 'pom.xml' → spring framework 버전 - 5.3.19
2022.08.02 - [백엔드 보고/스프링 (Spring)] - 프로젝트 개발 기준
프로젝트 개발 기준
앞으로 올리는 보물들은 아래 기준으로 업데이트 할 예정입니다. 참고해주세용!! * Windows 10 Pro (64Bit 운영체제) * 전자정부 프레임워크 (링크: https://www.egovframe.go.kr/) - 표준프레임워크 개발자 교.
bogoitsaw.tistory.com
My-SQL 셋팅: mysql 프로그램이 활성화되어있는 상태.
2022.08.04 - [백엔드 보고/My SQL (DB)] - My-SQL 셋팅
My-SQL 셋팅
처음 설치한다 가정하구, 접속하는것부터 시작해볼게용!~ ★ 사전설정 2022.08.02 - [백엔드 보고/스프링 (Spring)] - 프로젝트 개발 기준 ★ My-SQL 접속하기 mysql 접속하기 위해 cmd창을 띄워봅시닷! cmd
bogoitsaw.tistory.com
★ DB 생성 (필요한 경우에만 골라서 쓰세용)
create database test;
CREATE TABLE Test
(
`test_seq` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(45) NULL,
`title` VARCHAR(45) NULL,
PRIMARY KEY (test_seq)
);
INSERT INTO Test (name, title) VALUES ('name 02', 'title 02');
INSERT INTO Test (name, title) VALUES ('name 03', 'title 03');
INSERT INTO Test (name, title) VALUES ('name 04', 'title 04');
INSERT INTO Test (name, title) VALUES ('name 05', 'title 05');
INSERT INTO Test (name, title) VALUES ('name 06', 'title 06');
INSERT INTO Test (name, title) VALUES ('name 07', 'title 07');
INSERT INTO Test (name, title) VALUES ('name 08', 'title 08');
INSERT INTO Test (name, title) VALUES ('name 09', 'title 09');
INSERT INTO Test (name, title) VALUES ('name 10', 'title 10');
INSERT INTO Test (name, title) VALUES ('name 11', 'title 11');
INSERT INTO Test (name, title) VALUES ('name 12', 'title 12');
INSERT INTO Test (name, title) VALUES ('name 13', 'title 13');
INSERT INTO Test (name, title) VALUES ('name 14', 'title 14');
INSERT INTO Test (name, title) VALUES ('name 15', 'title 15');
★ 틀
- 폴더생성 하는 법을 모르시는 분들은 아래 '더보기' 참고해주세용
Domain폴더 만드는 예시


■ pom.xml (아래 시작하기 전에, 반드시 이거먼저 복붙 해주세요)
※ 유지보수를 위해, 필요한 내용만 빼서 올립니다.
- 넣을 내용
<!-- Lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.16</version>
<scope>provided</scope>
</dependency>
<!-- Hikari CP -->
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>3.4.1</version>
</dependency>
<!-- MyBatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<!-- MyBatis-Spring연결 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.2</version>
</dependency>
<!-- Spring DB처리 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.14.RELEASE</version>
</dependency>
<!-- MySQL JDBC Driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
- 넣을 위치
적용방법 모르시는분은 아래 더보기 클릭


이렇게 해도 업데이트가 안되면, '그림2'에서 아랫 부분을 보면 체크박스가 있는데, 아래에서 4번째 체크박스 'Focre Update of Snapshots/releases'를 체크해주시구 'OK'버튼 눌러주세요.
■ Domain / Test.java
package com.test.Domain;
import lombok.Data;
@Data
public class Test {
private int test_seq;
private String name;
private String title;
}
- java파일 생성 하는 법(보통, 아래 더보기에 나와있는것처럼 java파일을 생성합니다.)
Test.java파일 생성 예시



■ Mapper / TestMapper.java
이것도 java파일이지만, 인터페이스입니다. 인터페이스 생성하는 방법 모르시면 아래 더보기 클릭!



- 복붙할 내용
package com.test.Mapper;
import java.util.List;
import com.test.Domain.Test;
public interface TestMapper {
public List<Test> selectAllTest();
public void insertTest(Test test);
public void updateTest(Test test);
public void deleteTest(int test_seq);
}
■ Mapper / TestMapper.xml
- 이것도 mybatis에서 제공하는 xml파일을 생성해야하므로, 이 xml파일을 생성하는걸 모르는분들 위해 아래 '더보기'에 설명해두었습니다.



<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.test.Mapper.TestMapper">
<select id="selectAllTest" resultType="com.test.Domain.Test">
SELECT * from test
</select>
<insert id = "insertTest" parameterType = "com.test.Domain.Test">
INSERT INTO Test (name, title) VALUES (#{name}, #{title})
</insert>
<update id = "updateTest" parameterType = "com.test.Domain.Test">
update test set name = #{name}, title = #{title} where test_seq = #{test_seq}
</update>
<delete id = "deleteTest" parameterType = "int">
delete from test where test_seq = #{test_seq}
</delete>
</mapper>
■ Service / TestService.java
package com.test.Service;
import java.util.List;
import javax.inject.Inject;
import org.springframework.stereotype.Service;
import com.test.Domain.Test;
import com.test.Mapper.TestMapper;
@Service
public class TestService {
@Inject
private TestMapper mapper;
public List<Test> selectAllTest() throws Exception{
return mapper.selectAllTest();
}
public void insertTest(Test test){
mapper.insertTest(test);
}
public void updateTest(Test test){
mapper.updateTest(test);
}
public void deleteTest(int test_seq){
mapper.deleteTest(test_seq);
}
}
■ Controller / HomeController.java
package com.test.Controller;
import java.util.List;
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 org.springframework.web.bind.annotation.RequestMethod;
import com.test.Domain.Test;
import com.test.Service.TestService;
/**
* Handles requests for the application home page.
*/
@Controller
public class HomeController {
@Autowired
private TestService service;
@RequestMapping(value = {"/","/home"}, method = RequestMethod.GET)
public String home(Model model) throws Exception{
List<Test> selectAllTest = service.selectAllTest();
model.addAttribute("test", selectAllTest);
return "home";
}
@RequestMapping("/insertTest.do")
public String insertTest(Test test) {
service.insertTest(test);
return "redirect:/";
}
@RequestMapping("/updateTest.do")
public String updateTest(Test test) {
service.updateTest(test);
return "redirect:/";
}
@RequestMapping("/deleteTest.do")
public String deleteTest(int test_seq) {
service.deleteTest(test_seq);
return "redirect:/";
}
}
■ spring / appServlet / servlet-context.xml
<context:component-scan base-package="com.test.Service" />
■ spring/ root-context.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"
xmlns:mybatis="http://mybatis.org/schema/mybatis-spring"
xsi:schemaLocation="
http://mybatis.org/schema/mybatis-spring
http://mybatis.org/schema/mybatis-spring.xsd
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 -->
<!-- DB 연결(JDBC=Connection) API(HikariCP API) -->
<bean id="hikariConfig" class="com.zaxxer.hikari.HikariConfig">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test"/>
<property name="username" value="root"/>
<property name="password" value=""/>
</bean>
<bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close">
<constructor-arg ref="hikariConfig" />
</bean>
<!-- mybatis-spring API(Spring bridge for MyBatis sql mapping framework) -->
<bean class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- SqlSessionFactoryBean와 BoardMapper(SQL)와 연결 -->
<mybatis:scan base-package="com.test.Mapper"/>
</beans>
- 변동 될 수 있는 부분
1)
<property name="username" value="root"/>
<property name="password" value=""/>
mysql에서 설정한 비밀번호를 name = "password"의 value 안에 넣어주세요!
2)
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test"/>
mysql이라 이렇게 쓰이는데, oracle이나 mariadb같이 다른 DB로 쓰일 경우 이부분 달라질 수 있어요!
name부분에 jdbcUrl의 값에서 가장 오른쪽 test 부분은 데이터베이스 이름입니다. 3306은 포트번호구요.
■ web.xml
만들자마자 web.xml에 오류가 나오는데, 맨위에 세미콜론(;)을 추가해주어야 오류 안나옵니다.
<!--한글 인코딩 설정-->
<filter>
<filter-name>encoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
- DB에 넣고 뺄 때 한글인코딩 처리
■ views / home.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:set var="cpath" value="${pageContext.request.contextPath}" />
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Home</title>
</head>
<body>
<table>
<c:forEach items="${requestScope.test }" var="vo">
<tr>
<td class="no">${pageScope.vo.test_seq }</td>
<td >${vo.name }</td>
<td >${vo.title }</td>
</tr>
</c:forEach>
</table>
<form action="${cpath}/insertTest.do" method="post">
<input type = "text" name = "name" placeholder = "추가할 이름을 입력하세요.">
<input type = "text" name = "title" placeholder = "추가할 제목을 입력하세요.">
<button type="submit">추가하기</button>
</form>
<form action="${cpath}/updateTest.do" method="post">
<input type = "text" name = "test_seq" placeholder = "수정할 번호를 입력하세요.">
<input type = "text" name = "name" placeholder = "수정할 이름을 입력하세요.">
<input type = "text" name = "title" placeholder = "수정할 제목을 입력하세요.">
<button type="submit">수정하기</button>
</form>
<form action="${cpath}/deleteTest.do" method="post">
<input type = "text" name = "test_seq" placeholder = "삭제할 번호를 입력해주세요.">
<button type="submit">삭제하기</button>
</form>
</body>
</html>
Tip) 간단설명
- views / home.jsp
<form action="${cpath}/insertTest.do" method="post">
<input type = "text" name = "name" placeholder = "추가할 이름을 입력하세요.">
<input type = "text" name = "title" placeholder = "추가할 제목을 입력하세요.">
<button type="submit">추가하기</button>
</form>
- Mapper/ TestMapper.xml
<insert id = "insertTest" parameterType = "com.test.Domain.Test">
INSERT INTO Test (name, title) VALUES (#{name}, #{title})
</insert>
- Domain/ Test.java
private int test_seq;
private String name;
private String title;
여기 insert부분만 가져와써요!!
home.jsp에서 input 태그안의 name 속성들의 값은, Domain/Test.java와 TestMapper.xml에있는 변수들에게 그대로 들어갑니다. 그러니, views안에 jsp부분에서 input 태그들의 name부분의 변수이름이 위와 동일한 지 확인해봐야겠지요?
실행법을 모르시는 분들은 아래 '더보기'




'백엔드 보고 > My SQL (DB)' 카테고리의 다른 글
Heidi SQL (0) | 2022.08.05 |
---|---|
My-SQL 셋팅 (0) | 2022.08.04 |