반응형

https://penthegom.tistory.com/48

 

[Spring Boot]Spring MVC JSP 웹 튜토리얼(인텔리제이용 intelliJ) - 1

이 글에서는 스프링 부트 프레임 워크를 사용하여 스프링 MVC 웹 애플리케이션을 만들고 부트 스트랩하는 방법을 설명하겠다. JSP를 웹 애플리케이션의보기로 사용합니다. 이 응용 프로그램에 사용되는 도구 및 기..

penthegom.tistory.com

앞서 기본 Spring Boot MVC 를 만들어봤다. 이어서 이제 Mybatis와 PostgreSQL을 연결하는 방법을 설명하겠다.

이 응용 프로그램에 사용되는 도구 및 기술은 다음과 같다.

 

  • Spring Boot 2.1.x
  • Tomcat Embedded (Spring Boot 내장)
  • JavaSE 1.8
  • Maven
  • Mybatis
  • PostgreSQL 9.6.15
  • IntelliJ IDEA Ultimate 

 

프로젝트 구조(TREE)

1. DB설치 및 테이블 생성

Oracle, PostgreSQL, MySQL 등등 DB툴을 설치 해야한다. 여기서는 PostgreSQL을 사용하기로 한다.

이번 튜토리얼을 하기 위해 test라는 DB스키마를 생성한다.

 

1
2
3
4
5
6
7
8
CREATE TABLE test (
    id integer NOT NULL,
    name varchar NULL,
    CONSTRAINT test_pkey PRIMARY KEY (id)
);
 
INSERT INTO test (id, "name")
VALUES(1'펜다곰'),(2'홍길동');
cs

 

2. 각종 소스

 

- pom.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<?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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.8.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.penthegom.example</groupId>
    <artifactId>penthegomdemo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>penthegomdemo</name>
    <description>Demo project for Spring Boot</description>
 
    <properties>
        <java.version>1.8</java.version>
    </properties>
 
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
 
        <!-- JSP -->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>
    </dependencies>
 
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
 
</project>
 
cs

 

- application.yml(application.properties 를 application.yml로 변경후 적읍시다! 한글주석과 트리형태로 관리가 됩니다.)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
spring:
  mvc:
    view:
      prefix: /WEB-INF/views/
      suffix: .jsp
    static-path-pattern: /resources/**
  #DB 설정
  datasource:
    url: jdbc:postgresql://127.0.0.1:5432/tutorial
    driver-class-name: org.postgresql.Driver
   username: penthegom
   password: penthegom
  #JSP 바로적용 설정
  devtools:
    livereload:
      enabled: true
#로그 레벨
logging:
  level:
    # 쿼리 보기
    com.penthegom.example.penthegomdemo: DEBUG
 
cs

 

 

- DatabaseConfig.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package com.penthegom.example.penthegomdemo.config;
 
import javax.sql.DataSource;
 
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.transaction.annotation.EnableTransactionManagement;
 
@Configuration
@MapperScan(basePackages="com.penthegom.example.penthegomdemo.mapper")
@EnableTransactionManagement
public class DatabaseConfig {
 
    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        sessionFactory.setMapperLocations(resolver.getResources("classpath:mapper/postgresql/*.xml"));
        return sessionFactory.getObject();
    }
    
    @Bean
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) throws Exception {
      final SqlSessionTemplate sqlSessionTemplate = new SqlSessionTemplate(sqlSessionFactory);
      return sqlSessionTemplate;
    }
}
cs

 

- HelloController.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package com.penthegom.example.penthegomdemo.controller;
 
import com.penthegom.example.penthegomdemo.dto.Test;
import com.penthegom.example.penthegomdemo.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
 
import java.util.List;
 
@Controller
public class HelloController {
 
    @Autowired
    TestService testService;
 
    @RequestMapping("/")
    public String index() {
 
        return "index";
    }
 
    @RequestMapping("/query")
    public @ResponseBody
    List<Test> query() throws Exception{
        return testService.getAll();
    }
}
 
cs

 

- Test.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package com.penthegom.example.penthegomdemo.dto;
 
public class Test {
    private String id;
    private String name;
 
    public String getId() {
        return id;
    }
 
    public void setId(String id) {
        this.id = id;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
}
cs

 

- TestMapper.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package com.penthegom.example.penthegomdemo.mapper;
 
import java.util.List;
 
import com.penthegom.example.penthegomdemo.dto.Test;
import org.springframework.stereotype.Repository;
 
@Repository
public interface TestMapper {
 
    public List<Test> getAll() throws Exception;
    
}
 
cs

 

- TestService.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.penthegom.example.penthegomdemo.service;
 
import java.util.List;
 
import com.penthegom.example.penthegomdemo.dto.Test;
import com.penthegom.example.penthegomdemo.mapper.TestMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
 
@Service
public class TestService {
 
    @Autowired
    TestMapper testMapper;
    
    public List<Test> getAll() throws Exception{
        return testMapper.getAll();
    }
}
 
cs

 

- test.xml

1
2
3
4
5
6
7
<?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.penthegom.example.penthegomdemo.mapper.TestMapper">
    <select id="getAll" resultType="com.penthegom.example.penthegomdemo.dto.Test">
        SELECT * FROM test
    </select>
</mapper>
cs

 

3. 실행 결과

 

반응형

+ Recent posts