목차 | |
1. | 설정 |
2. | 기초 |
1. 설정
새로운 Spring Legacy Project를 생성할 때
2. 기초
▣ sqlFile
-- 241029
create table board(
bno bigint auto_increment,
title varchar(500) not null,
writer varchar(500) not null,
content text,
is_del varchar(5) default 'N',
reg_date datetime default now(),
read_cout int default 0,
primary key(bno));
▣ pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ezen</groupId>
<artifactId>spring</artifactId>
<name>spring_study_javaClass</name>
<packaging>war</packaging>
<version>1.0.0-BUILD-SNAPSHOT</version>
<properties>
<java-version>11</java-version>
<org.springframework-version>5.3.10</org.springframework-version>
<org.aspectj-version>1.6.10</org.aspectj-version>
<org.slf4j-version>2.0.7</org.slf4j-version>
</properties>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework-version}</version>
<exclusions>
<!-- Exclude Commons Logging in favor of SLF4j -->
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<!-- AspectJ -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${org.aspectj-version}</version>
</dependency>
<!-- Logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j-version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${org.slf4j-version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${org.slf4j-version}</version>
<scope>runtime</scope>
</dependency>
<!-- logback-classic 1.4.5 / logback-core / log4jdbc-log4j2-jdbc4.1-1.16 -->
<!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-classic -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.4.5</version>
<!-- <scope>test</scope> -->
</dependency>
<!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-core -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.4.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.bgee.log4jdbc-log4j2/log4jdbc-log4j2-jdbc4.1 -->
<dependency>
<groupId>org.bgee.log4jdbc-log4j2</groupId>
<artifactId>log4jdbc-log4j2-jdbc4.1</artifactId>
<version>1.16</version>
</dependency>
<!-- <dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.15</version>
<exclusions>
<exclusion>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
</exclusion>
<exclusion>
<groupId>javax.jms</groupId>
<artifactId>jms</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jdmk</groupId>
<artifactId>jmxtools</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jmx</groupId>
<artifactId>jmxri</artifactId>
</exclusion>
</exclusions>
<scope>runtime</scope>
</dependency> -->
<!-- @Inject -->
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
<!-- Servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- Test -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.7</version>
<scope>test</scope>
</dependency>
<!-- 여기서부터 추가 dependency -->
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.34</version>
<scope>provided</scope>
</dependency>
<!-- DB 관련 -->
<!-- mysql-connector-j-8.0.33 / mybatis-3.5.10 / mybatis-spring-2.0.6 -->
<!-- https://mvnrepository.com/artifact/com.mysql/mysql-connector-j -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.0.33</version>
</dependency>
<!-- spring-JDBC-5.3.10 / spring-Test-5.3.10 -->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${org.springframework-version}</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.10</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<!-- Hikari CP -->
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>6.0.0</version>
</dependency>
<!-- 댓글관련, 파일관련, 시큐리티관련, 스케쥴러관련 -->
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-eclipse-plugin</artifactId>
<version>2.9</version>
<configuration>
<additionalProjectnatures>
<projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
</additionalProjectnatures>
<additionalBuildcommands>
<buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
</additionalBuildcommands>
<downloadSources>true</downloadSources>
<downloadJavadocs>true</downloadJavadocs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<source>11</source>
<target>11</target>
<compilerArgument>-Xlint:all</compilerArgument>
<showWarnings>true</showWarnings>
<showDeprecation>true</showDeprecation>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<configuration>
<mainClass>org.test.int1.Main</mainClass>
</configuration>
</plugin>
<!-- 플러그인 추가 : web.xml이 없어도 class를 통해서 설정정보를 읽을 수 있게 추가 설정-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.4.0</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
</project>
▣ ServeltConfiguration.java
package com.ezen.spring.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
@EnableWebMvc
@ComponentScan(basePackages = {"com.ezen.spring.controller","com.ezen.spring.service","com.ezen.spring.handler"})
public class ServletConfiguration implements WebMvcConfigurer{
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// resources 경로 설정 (css, js, img, font)
registry.addResourceHandler("/resources/**").addResourceLocations("/resouces/");
// 나중에 파일 업로드 경로도 추가 예정
}
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
// view를 jsp(jstl 포함)로 어떻게 보여줄지 설정
// view 경로 설정
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
// 화면에 뷰를 구성할 때 jstl에 대한 사용을 하는 jsp를 구성하겠다.
viewResolver.setViewClass(JstlView.class);
registry.viewResolver(viewResolver);
}
// 나중에 파일 업로드 리졸버도 추가 예정.
}
▣ RootConfig.java
package com.ezen.spring.config;
import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
@EnableTransactionManagement
@MapperScan(basePackages = {"com.ezen.spring.dao"})
@Configuration
public class RootConfig {
// @Autowired : 해당 객체를 스프링 객체로 생성
@Autowired
ApplicationContext applicationContext;
// DB에 관련된 설정 : 사용자가 만든 객체를 스프링이 인지하도록 설정 => @Bean
@Bean
public DataSource dataSource() {
HikariConfig hikariConfig = new HikariConfig();
// com.mysql.cj.jdbc.Driver 대신 log4jdbc 드라이버 사용
// log4jdbc 드라이버 => DB의 흐름으로 로그로 찍어주는 드라이버.
// springdb / springUser / mysql
hikariConfig.setDriverClassName("net.sf.log4jdbc.sql.jdbcapi.DriverSpy");
hikariConfig.setJdbcUrl("jdbc:log4jdbc:mysql://localhost:3306/springdb2");
hikariConfig.setUsername("springUser");
hikariConfig.setPassword("mysql");
// -- 여기서부터 hikari 추가 설정
hikariConfig.setMaximumPoolSize(5); // 한 번에 설정할 최대 커넥션 개수
hikariConfig.setMinimumIdle(5); // 최소 유휴 커넥션 수 (max와 같은 개수로 설정)
hikariConfig.setConnectionTestQuery("SELECT now()"); // 첫 연결시 test sql
hikariConfig.setPoolName("springHikariCP");
// -- 여기서부터 추가설정
// cachePrepStmts : cache 사용여부 설정
hikariConfig.addDataSourceProperty("dataSource.cachePrepStmts", "true");
// mysql 드라이버가 연결당 cache 사이즈 설정 : 250~500사이 권장
hikariConfig.addDataSourceProperty("dataSource.PrepStmtsCacheSize", "250");
// connection당 캐싱할 prearedStatement 개수 지정 옵션 : default 250
hikariConfig.addDataSourceProperty("dataSource.prepStmtsCacheSqlLimit", "true");
// mysql 서버에서 최신 이슈가 있을 경우 지원을 받을 것인지 설정
hikariConfig.addDataSourceProperty("dataSource.useServerPrepStmts", "true");
HikariDataSource hikariDataSource = new HikariDataSource(hikariConfig);
return hikariDataSource;
}
@Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
SqlSessionFactoryBean sqlFactoryBean = new SqlSessionFactoryBean();
sqlFactoryBean.setDataSource(dataSource());
// 내부 src/main/resources의 위치값이 필요
sqlFactoryBean.setMapperLocations(applicationContext.getResources("classpath:/mappers/*.xml"));
// DB: _ (스네이크 표기법) / java : 카멜표기법 reg_date(스네이크케이스) = regDate(카멜케이스)
sqlFactoryBean.setConfigLocation(applicationContext.getResource("classpath:/mybatisConfig.xml"));
return sqlFactoryBean.getObject();
}
// 트랜잭션 매니저 설정
@Bean
public DataSourceTransactionManager transactionManager() {
return new DataSourceTransactionManager(dataSource());
}
}
▣ mybatisConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
</configuration>
<!-- <typeAliases>
<typeAlias type="com.ezen.spring.domain.BoardVO" alias="bvo/>
</typeAliases > -->
▣ ServletConfiguration.java
package com.ezen.spring.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
@EnableWebMvc
@ComponentScan(basePackages = {"com.ezen.spring.controller","com.ezen.spring.service","com.ezen.spring.handler"})
public class ServletConfiguration implements WebMvcConfigurer{
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// resources 경로 설정 (css, js, img, font)
registry.addResourceHandler("/resources/**").addResourceLocations("/resouces/");
// 나중에 파일 업로드 경로도 추가 예정
}
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
// view를 jsp(jstl 포함)로 어떻게 보여줄지 설정
// view 경로 설정
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
// 화면에 뷰를 구성할 때 jstl에 대한 사용을 하는 jsp를 구성하겠다.
viewResolver.setViewClass(JstlView.class);
registry.viewResolver(viewResolver);
}
// 나중에 파일 업로드 리졸버도 추가 예정.
}
▣ HomeController.java
package com.ezen.spring.controller;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* Handles requests for the application home page.
*/
@Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
/**
* Simply selects the home view to render by returning its name.
*/
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
logger.info("Welcome home! The client locale is {}.", locale);
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
model.addAttribute("serverTime", formattedDate );
return "index";
}
}
▣ BoardVO.java
package com.ezen.spring.domain;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class BoardVO {
// bno bigint auto_increment,
// title varchar(500) not null,
// writer varchar(500) not null,
// content text,
// is_del varchar(5) default 'N',
// reg_date datetime default now(),
// read_cout int default 0,
private long bno;
private String title;
private String writer;
private String content;
private String isDel;
private String regDate;
private int readCount;
}
▣ BoardController.java
package com.ezen.spring.controller;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import com.ezen.spring.domain.BoardVO;
import com.ezen.spring.service.BoardService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@RequiredArgsConstructor
@RequestMapping("/board/*")
@Controller
public class BoardController {
// 생성자 주입시 객체는 final로 생성
private final BoardService bsv;
// return void => 온 경로 그대로 리턴 /board/register => /board/register.jsp
@GetMapping("/register")
public void register() {}
@PostMapping("/insert")
public String insert(BoardVO bvo) {
log.info(">>> insert bvo > {}", bvo);
int isOk = bsv.insert(bvo);
log.info(">>> insert > {}", isOk > 0 ? "OK" : "FAIL");
// /WEB-INF/views/.jsp (x)
// 컨트롤러의 mapping 위치로 연결할 때 redirect:/board/list
return "redirect:/";
}
@GetMapping("/list")
public String list(Model m) {
// request.setAttrbute()
// Model 객체가 해당 일을 대신해줌.
List<BoardVO> list = bsv.getList();
m.addAttribute("list",list);
return "/board/list";
}
}
▣ index.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<jsp:include page="layout/header.jsp"/>
<div class="container-md">
<P> The time on the server is ${serverTime}. </P>
</div>
<jsp:include page="layout/footer.jsp"/>
▣ header.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c "%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>header.jsp</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
</head>
<body>
<!-- <div class="container-md"> -->
<h1>
My Spring Project!!
</h1>
<!-- </div> -->
<nav class="navbar navbar-expand-lg bg-body-tertiary">
<div class="container-fluid">
<a class="navbar-brand" href="#">Spring</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/board/register">게시판 글쓰기</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/board/list">게시판 보기</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
</ul>
</div>
</div>
</nav>
▣ footer.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c "%>
<!DOCTYPE html>
<div class="container-md">
2024 spring project...
</div>
</body>
</html>
▣ reigster.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c "%>
<div class="container-md">
<jsp:include page="../layout/header.jsp"/>
<form action="/board/insert" method="post">
<div class="mb-3">
<label for="t" class="form-label">title</label>
<input type="text" class="form-control" id="t" name="title" placeholder="title...">
</div>
<div class="mb-3">
<label for="w" class="form-label">writer</label>
<input type="text" class="form-control" id="w" name="writer" placeholder="writer...">
</div>
<div class="mb-3">
<label for="c" class="form-label">content</label>
<textarea class="form-control" id="c" rows="3" name="content" ></textarea>
</div>
<button type="submit" class="btn btn-primary">register</button>
</form>
</div>
<jsp:include page="../layout/footer.jsp"/>
</body>
</html>
▣ list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<jsp:include page="../layout/header.jsp"/>
<div class="container-md">
<table class="table table-hover">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">title</th>
<th scope="col">writer</th>
<th scope="col">regDate</th>
<th scope="col">readCount</th>
</tr>
</thead>
<tbody>
<c:forEach items="${list}" var="bvo">
<tr>
<td>${bvo.bno }</td>
<td><a>${bvo.title }</a></td>
<td>${bvo.writer }</td>
<td>${bvo.regDate }</td>
<td>${bvo.readCount }</td>
</tr>
</c:forEach>
</tbody>
</table>
<a href="/"><button type="submit" class="btn btn-success">list</button></a>
</div>
<jsp:include page="../layout/footer.jsp"/>
▣ BoardService.java
package com.ezen.spring.service;
import java.util.List;
import com.ezen.spring.domain.BoardVO;
public interface BoardService {
int insert(BoardVO bvo);
List<BoardVO> getList();
}
▣ BoardServiceImpl.java
package com.ezen.spring.service;
import java.util.List;
import org.springframework.stereotype.Service;
import com.ezen.spring.dao.BoardDAO;
import com.ezen.spring.domain.BoardVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@RequiredArgsConstructor
@Slf4j
@Service
public class BoardServiceImpl implements BoardService{
private final BoardDAO bdao;
@Override
public int insert(BoardVO bvo) {
// TODO Auto-generated method stub
return bdao.insert(bvo);
}
@Override
public List<BoardVO> getList() {
// TODO Auto-generated method stub
return bdao.getList();
}
}
▣ BoardDAO.java
package com.ezen.spring.dao;
import java.util.List;
import com.ezen.spring.domain.BoardVO;
public interface BoardDAO {
int insert(BoardVO bvo);
List<BoardVO> getList();
}
▣ boardMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- DAOImpl() 없음. => namespace="다오인터페이스명" id="메서드명" -->
<mapper namespace="com.ezen.spring.dao.BoardDAO">
<insert id="insert">
insert into board(title, writer, content)
values(#{title}, #{writer}, #{content})
</insert>
<select id="getList" resultType="com.ezen.spring.domain.BoardVO">
select * from board where is_del = 'N' order by bno desc limit 0, 10
</select>
</mapper>
▣ BoardTest.java
package com.ezen.spring.repos;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.ezen.spring.dao.BoardDAO;
import com.ezen.spring.domain.BoardVO;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {com.ezen.spring.config.RootConfig.class})
public class BoardTest {
@Autowired
private BoardDAO bdao;
@Test
public void insertBoardDummies() {
for(int i=0; i<5000; i++) {
BoardVO bvo = new BoardVO();
bvo.setTitle("Test Title"+ i);
bvo.setWriter("tester" + ((int)(Math.random()*500)+1) + "@tester.com");
bvo.setContent("Test Content ... " + i);
bdao.insert(bvo);
}
}
}
▷ 출력
'Java > Spring' 카테고리의 다른 글
Spring 기초(scheduler) - AWS 풀스택 과정 70일차 (0) | 2024.11.04 |
---|---|
Spring 기초(file) - AWS 풀스택 과정 69일차 (0) | 2024.11.01 |
Spring 기초(comment) - AWS 풀스택 과정 68일차 (0) | 2024.10.31 |
Spring 기초(paging, search) - AWS 풀스택 과정 67일차 (0) | 2024.10.30 |
Spring 설정 및 기초 - AWS 풀스택 과정 65일차 (0) | 2024.10.28 |