๋ณธ๋ฌธ์œผ๋กœ ๋ฐ”๋กœ๊ฐ€๊ธฐ

[DB] Mybatis๋ž€?

category DB/DataAccess 2022. 8. 24. 09:42

ORM(Object Relational Mapping)

๐Ÿ’ก ๊ฐ์ฒด์™€ ๊ด€๊ณ„ํ˜• ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์˜ ๋ฐ์ดํ„ฐ๋ฅผ ์ž๋™์œผ๋กœ ๋งคํ•‘(์—ฐ๊ฒฐ)ํ•ด์ฃผ๋Š” ๊ธฐ์ˆ 

  • ๊ฐ์ฒด ๋ชจ๋ธ(๊ฐ์ฒด ์ง€ํ–ฅ ํ”„๋กœ๊ทธ๋ž˜๋ฐ์˜ ํด๋ž˜์Šค)๊ณผ ๊ด€๊ณ„ํ˜• ๋ชจ๋ธ(๊ด€๊ณ„ํ˜• ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์˜ ํ…Œ์ด๋ธ”) ๊ฐ„์˜ ๋ถˆ์ผ์น˜ ์กด์žฌ
  • ORM์„ ํ†ตํ•ด ๊ฐ์ฒด ๊ฐ„์˜ ๊ด€๊ณ„๋ฅผ ๋ฐ”ํƒ•์œผ๋กœ SQL์„ ์ž๋™์œผ๋กœ ์ƒ์„ฑํ•˜์—ฌ ๋ถˆ์ผ์น˜ ํ•ด๊ฒฐ
  • ๋Œ€ํ‘œ์ ์ธ ๊ธฐ์ˆ ๋กœ JPA ๋“ฑ์ด ์žˆ์ง€๋งŒ Mybatis๋Š” ์ง์ ‘ ์ฟผ๋ฆฌ๋ฅผ ๋ช…์‹œํ•˜๊ธฐ ๋•Œ๋ฌธ์— ORM์œผ๋กœ ๋ณด๊ธฐ ํž˜๋“ฆ

Mybatis๋ž€

  • ์ž๋ฐ”์˜ ๊ด€๊ณ„ํ˜• ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ํ”„๋กœ๊ทธ๋ž˜๋ฐ์„ ๋” ์‰ฝ๊ฒŒ ํ•  ์ˆ˜ ์žˆ๋„๋ก ๋„์™€์ฃผ๋Š” ํ”„๋ ˆ์ž„์›Œํฌ
  • ๋ณต์žกํ•œ JDBC ์ฝ”๋“œ๋ฅผ ๊น”๋”ํ•˜๊ฒŒ ์œ ์ง€ํ•  ์ˆ˜ ์žˆ๋„๋ก ํ•ด์คŒ(JDBC์˜ ๋ชจ๋“  ๊ธฐ๋Šฅ์„ ์ œ๊ณต)
  • ์ž๋ฐ”์˜ ๊ฐ์ฒด(Object)์™€ SQL ์‚ฌ์ด์— ์ž๋™ ๋งคํ•‘

 

gradle

// Mybatis ์ถ”๊ฐ€
implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:2.1.4'

 

application.properties

// JDBC ๋“œ๋ผ์ด๋ฒ„ ํด๋ž˜์Šค ์ด๋ฆ„ ์ง€์ •: MySQL JDBC Driver
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

// DB์˜ IP์™€ ์Šคํ‚ค๋งˆ ์ด๋ฆ„ ์ง€์ •
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=yes&characterEncoding=UTF-8

// DB์— ์—ฐ๊ฒฐํ•  ๊ณ„์ • ์„ค์ •
spring.datasource.username=root
spring.datasource.password=root

// xml์—์„œ ์ฟผ๋ฆฌ ์ž‘์„ฑ ์‹œ, resultType์ด ์œ„์น˜ํ•˜๋Š” ๊ฒฝ๋กœ ์ž‘์„ฑ -> Mybatis๊ฐ€ ์ฐพ์•„์„œ ๋งคํ•‘ 
mybatis.type-aliases-package=com.example.demo.model 

 

User.java

@Getter
@Setter
public class User {
    private int id;
    private String name;
    private String part;
}

 

UserMapper.java

@Mapper
public interface UserMapper {
    List<Users> findAll();
        void userAdd(User user);
}
  • Spring IoC ์ปจํ…Œ์ด๋„ˆ์— Service Bean์œผ๋กœ ๋“ฑ๋ก
  • ํ•ด๋‹น ์ธํ„ฐํŽ˜์ด์Šค์— ๋“ฑ๋ก๋œ SQL Annotation์„ ๋ฐ”ํƒ•์œผ๋กœ ์‹ค์ œ SQL๋ฌธ์„ ์‹คํ–‰์‹œํ‚ด

 

UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="test.demo.mapper.UserMapper">
    <select id="findALl" resultType="User">
        SELECT * FROM user;
    </select>

        <insert id="userAdd">
            INSERT user (name, part) VALUES (#{name}, #{part})
        </insert>
</mapper>
  • namespace: UserMapper ์ธํ„ฐํŽ˜์ด์Šค๊ฐ€ ์กด์žฌํ•˜๋Š” ๊ฒฝ๋กœ ์ง€์ •
  • id: @Mapper๊ฐ€ ์žˆ๋Š” ์ธํ„ฐํŽ˜์ด์Šค์—์„œ ์‚ฌ์šฉํ•œ ๋ฉ”์†Œ๋“œ ์ด๋ฆ„ ์ง€์ •
  • resultType: ๋ฐ˜ํ™˜ ๊ฐ’ ํ˜• ์ง€์ •
    • ์ฟผ๋ฆฌ ๊ฒฐ๊ณผ๊ฐ€ ์ž๋™์œผ๋กœ ๋งคํ•‘๋˜์–ด ์ฑ„์›Œ์ง€๊ธฐ ๋•Œ๋ฌธ์—, DB ์ปฌ๋Ÿผ์˜ ๊ฒฐ๊ณผ์™€ resultType ํด๋ž˜์Šค์˜ setter ๋ฉ”์†Œ๋“œ๊ฐ€ ์ •ํ™•ํžˆ ์ผ์น˜ํ•ด์•ผ ํ•จ
  • #{ํ•„๋“œ๋ช…} : ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ ์ „๋‹ฌ ๋ฐ›์€ ๊ฐ์ฒด์˜ ํ•„๋“œ ๋™์  ๋ฐ”์ธ๋”ฉ

 

์ฐธ๊ณ 

 

'DB > DataAccess' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[DB] JDBC๋ž€?  (0) 2022.08.24