Spring Boot + myBatis 연동

꿈나무기록장·2022년 1월 17일
0

springboot

목록 보기
1/1
post-custom-banner

여기를 참고하였으나, thymeleaf를 사용하지 않고 jsp를 사용하여 연결하였다.

pom.xml 부분에 dependency 추가

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
				<!-- 			<scope>runtime</scope> -->
		</dependency>
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>2.0.0</version>
		</dependency>

		<!-- jsp viewer : jsp 사용을 위해 삽입-->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
		</dependency>

		<dependency>
			<groupId>org.apache.tomcat.embed</groupId>
			<artifactId>tomcat-embed-jasper</artifactId>
		</dependency>

		<!-- DevTools -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
		</dependency>

DTO

public class UserDTO {
	private String email;
	private int id;
    private String name;
    
	// getter, setter, tostring

DAO (Interface)

@Mapper
public interface UserDAOInterface {
		public List<UserDTO> listmap();
}

Mapper

<?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=" 'DAO path' + .UserDAOInterface" >

    <select id="listmap" resultType=" 'DTO path' + .UserDTO">
        select id,name,email from user
    </select>
    
</mapper>

application.properties

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://데이터베이스서버:3306/데이터베이스이름?serverTimezone=Asia/Seoul
spring.datasource.username=USER
spring.datasource.password=PASSWORD

mybatis.mapper-locations=classpath:mapper/*Mapper.xml

Controller

@Controller
public class UserControllerRDBS {

	@Autowired
	private UserDAOInterface userMapper;
	
	@RequestMapping("/listmap")
	public ModelAndView listmap(Model model) {
		ModelAndView mv = new ModelAndView();
		
		//model.addAttribute("list", userMapper.listmap());
		List<UserDTO> listmap = userMapper.listmap();
		System.out.println(listmap.toString());
		
		mv.addObject("listmap", listmap);
		
		mv.setViewName("listmap");
		
		return mv;
	}
}

JSP 파일 내용

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<table>
      <tr>
        <th>id</th>
        <th>name</th>
        <th>email</th>
      </tr>
      <tr>
        <td >${listmap[0].id}</td>
        <td >${listmap[0].name}</td>
        <td >${listmap[0].email}</td>
      </tr>
</table>

</body>
</html>
profile
초보자가 기록하는 곳
post-custom-banner

0개의 댓글