'전체 글'에 해당되는 글 120건

  1. 2019.03.29 스프링부트 로그 설정
  2. 2019.03.29 MyBatis Framework란 무엇인가?
  3. 2019.03.29 [Spring Boot] MyBatis + Mysql 샘플2
posted by 귀염둥이채원 2019. 3. 29. 18:19

1. application.properties 파일에 log 설정

logging.level.root=INFO 
logging.level.com.example.demo=ERROR 


2. HelloController.java 추가

package com.example.demo.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

	private static final Logger logger = LoggerFactory.getLogger(HelloController.class);
	
	@RequestMapping("/")
	public String index() {
		return "hello world!";
	}

	@RequestMapping("/log")
	public String log() {
		logger.debug("debug log");
		logger.info("info log");
		logger.warn("warn log");
		logger.error("error log");
		return "hello world!";
	}
}

 

'Spring Boot' 카테고리의 다른 글

[Spring Boot] MyBatis + Mysql 샘플2  (0) 2019.03.29
[Spring Boot] MyBatis + Mysql 샘플  (0) 2019.03.29
DAO, DTO, VO란?  (0) 2019.03.28
스프링 MVC 패턴이란?  (0) 2019.03.28
WEB MVC HelloWorld  (0) 2019.03.28
posted by 귀염둥이채원 2019. 3. 29. 17:10

# MyBatis Framework란?
1. 객체 지향 언어인 자바의 관계형 데이터 베이스 프로그래밍을 보다 쉽게 도와주는 프레임 워크
2. 자바에서는 관계형 데이터베이스 프로그래밍을 하기위해 JDBC를 제공
     ※ JDBC(Java Database Connectivity) : 자바 프로그램이 데이터베이스와 연결되어 데이터를 주고 받을 수 있게 해주는 프로그래밍 인터페이스
     (DriverClass, Connection, PreparedStatement, ResultSet etc)
3. JDBC는 다양한 관계형 데이터베이스 프로그래밍을 위해 API 제공
--> 결론 : MyBatis는 JDBC를 보다 편하게 사용하기 위해 개발

# MyBatis의 특징
1. SQL문이 코드로부터 완전히 분리
   - 기존에는 DAO파일에 모든 SQL문을 작성하였다. 
     하지만 MyBatis에서는 Mapper 파일에 SQL코드를 입력해 놓고 DAO 파일에서 필요할 때마다 가져와서 사용할 수 있다.
2. 생산성 
   - 코드가 짧아진다.
3. 유지보수성 향상
   - Mapper 파일에만 SQL 코드를 입력하고 나중에 SQL 코드를 변경할 때 이곳에서 유지보수만 하면, 

     DAO에서는 아무런 영향을 받지 않는다. 
     왜냐하면 DAO에서는 Mapper파일에서 작성된 SQL 코드를 갖다 쓰기만 하기 때문이다.

# Ibatis에서 MyBatis로 변경된 이유
-> Apache project팀에서 google code팀으로 이동하면서 명칭이 변경됨.


# 스프링부트에서 MyBatis 사용하기

https://doohwan-yoo.github.io/springboot-mybatis/
http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/
https://github.com/mybatis/spring-boot-starter/tree/master/mybatis-spring-boot-samples/mybatis-spring-boot-sample-annotation
https://github.com/mybatis/spring-boot-starter/tree/master/mybatis-spring-boot-samples/mybatis-spring-boot-sample-xml

# 참고 사이트
https://khj93.tistory.com/entry/MyBatis-MyBatis%EB%9E%80-%EA%B0%9C%EB%85%90-%EB%B0%8F-%ED%95%B5%EC%8B%AC-%EC%A0%95%EB%A6%AC
https://iotsw.tistory.com/79?category=717332

posted by 귀염둥이채원 2019. 3. 29. 16:02

스프링부트에서 MyBatis 샘플 프로그램입니다.

 

1. MySQL DDL & DML 생성

CREATE TABLE MEMBER (ID INT PRIMARY KEY, NAME VARCHAR(50), PHONE VARCHAR(20)); 

INSERT INTO MEMBER (ID, NAME, PHONE) VALUES (1, 'xml', '010-9912-1234'); 
INSERT INTO MEMBER (ID, NAME, PHONE) VALUES (2, 'annotation', '010-2333-4321'); 
mysql> desc MEMBER;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| ID    | int(11)     | NO   | PRI | NULL    |       |
| NAME  | varchar(50) | YES  |     | NULL    |       |
| PHONE | varchar(20) | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

mysql> select * from MEMBER;
+----+------------+---------------+
| ID | NAME       | PHONE         |
+----+------------+---------------+
|  1 | xml        | 010-9912-1234 |
|  2 | annotation | 010-2333-4321 |
+----+------------+---------------+
2 rows in set (0.00 sec)


2. pom.xml 파일에 dependency 추가 

	<dependencies>
		<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.0.0</version>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-tomcat</artifactId>
			<scope>provided</scope>
		</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>
		</dependency>
</dependencies>

3. application.yml 파일 생성

spring:
  datasource:
    driverClassName: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://172.21.111.144:3306/test
    username: root
    password: password
logging:
  level:
    #org.springframework.boot: DEBUG
    sample.springboot.mybatis: DEBUG


4. DataBaseConfig.java 파일 생성

package com.example.demo;

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.example.demo.dao")
@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:com/example/dao/*.xml"));
        return sessionFactory.getObject();
    }
    
    @Bean
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) throws Exception {
      final SqlSessionTemplate sqlSessionTemplate = new SqlSessionTemplate(sqlSessionFactory);
      return sqlSessionTemplate;
    }
}


5. Member.java 파일 생성 

package com.example.demo.model;

public class Member {
	private Long id;
	private String name;
	private String phone;
	
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	
	@Override
	public String toString() {
		return "Member [id=" + id + ", name=" + name + ", phone=" + phone + "]";
	}
}


6. MemberMapper.java 파일 생성

package com.example.demo.dao;

import java.util.List;

import org.apache.ibatis.annotations.Mapper;

import com.example.demo.model.Member;

@Mapper
public interface MemberMapper {
	List<Member> findAll();
	Member findById(Long id);
}


7. Member.xml 파일 생성

<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.example.demo.dao.MemberMapper">

	<select id="findAll" resultType="com.example.demo.model.Member">
		SELECT ID, NAME, PHONE FROM MEMBER
	</select>
  
	<select id="findById" resultType="com.example.demo.model.Member">
		SELECT ID, NAME, PHONE FROM MEMBER WHERE ID = #{id}
	</select>
  
</mapper>


8. MemberController.java 파일 생성

package com.example.demo.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.dao.MemberMapper;
import com.example.demo.model.Member;

@RestController
public class MemberController {
	
	@Autowired
	MemberMapper memberMapper;
	
	@RequestMapping("members")
	public List<Member> members() {
		return memberMapper.findAll();
	}
	
	@RequestMapping("member/{id}")
	public Member member(@PathVariable("id") Long id) {
		return memberMapper.findById(id);
	}
}


9. 실행 및 결과 확인
http://localhost:8080/members
[{"id":1,"name":"xml","phone":"010-9912-1234"},{"id":2,"name":"annotation","phone":"010-2333-4321"}]

http://localhost:8080/member/1
{"id":1,"name":"xml","phone":"010-9912-1234"}

# 참고
https://github.com/sbcoba/spring-boot-mybatis/   --> spring-boot-mybatis-sample-xml

'Spring Boot' 카테고리의 다른 글

스프링부트 로그 설정  (0) 2019.03.29
[Spring Boot] MyBatis + Mysql 샘플  (0) 2019.03.29
DAO, DTO, VO란?  (0) 2019.03.28
스프링 MVC 패턴이란?  (0) 2019.03.28
WEB MVC HelloWorld  (0) 2019.03.28