본문 바로가기
프로그래밍/Java

[Java]MyBatis와 JPA

by 시간많은백수 2023. 9. 26.
반응형

✔️MyBatis란?

  • MyBatis는 SQL 기반 데이터베이스 액세스를 위한 오픈 소스 프레임워크입니다.
  • MyBatis는 SQL 쿼리를 XML 또는 애노테이션을 통해 정의하고, Java 객체와 데이터베이스 레코드를 매핑합니다.
  • MyBatis는 개발자가 SQL을 직접 작성하고 실행하는 방식으로 데이터베이스와 상호 작용할 수 있게 합니다.
  • SQL 매핑과 데이터베이스 액세스를 세밀하게 제어할 수 있어 복잡한 쿼리와 성능 최적화에 용이합니다.

 

✔️JPA란?

  • **JPA (Java Persistence API)**는 자바 표준 ORM (Object-Relational Mapping) 스펙입니다.
  • JPA는 객체와 데이터베이스 간의 매핑을 자동화하고, SQL을 직접 작성하지 않고도 데이터베이스 액세스를 가능하게 합니다.
  • JPA 구현체 중 하나인 Hibernate는 가장 많이 사용되며, EclipseLink와 OpenJPA도 대안으로 사용됩니다.
  • JPA는 애플리케이션에서 엔티티 객체를 사용하여 데이터베이스와 상호 작용합니다.

 

💡MyBatis와 JPA 비교

  • 데이터베이스 액세스 방식
    • MyBatis: 개발자가 SQL을 직접 작성하고 실행하여 데이터베이스와 상호 작용합니다.
    • JPA: 객체와 데이터베이스 간의 매핑을 통해 객체를 데이터베이스에 저장하고 검색할 수 있게 합니다.
  • 매핑 방식
    • MyBatis: SQL 매핑을 XML 파일이나 애노테이션을 통해 정의하고, 객체와 데이터베이스 필드를 수동으로 매핑합니다.
    • JPA: 애노테이션을 사용하여 객체와 데이터베이스 테이블을 자동으로 매핑하며, 객체 간의 관계를 정의할 수 있습니다.
  • 복잡한 쿼리
    • MyBatis: 복잡한 SQL 쿼리를 작성하고 세밀하게 제어할 수 있어 데이터베이스 특화 작업에 유용합니다.
    • JPA: 단순한 쿼리는 간단한 애노테이션만으로 처리할 수 있지만, 복잡한 쿼리에 대해서는 JPQL (Java Persistence Query Language)을 사용하여 처리합니다.
  • 생산성
    • MyBatis: SQL을 직접 작성하므로 개발자가 데이터베이스에 대한 깊은 이해가 필요하며, 복잡한 작업에 대한 구현이 더욱 유연합니다.
    • JPA: 객체 중심의 개발을 지원하므로 개발 생산성이 향상되며, 간단한 CRUD (Create, Read, Update, Delete) 작업에 적합합니다.

💡MyBatis 사용 예)

1.프로젝트 설정

Maven 프로젝트를 생성하고, MyBatis와 JDBC 드라이버 의존성을 추가합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<dependencies>
    <!-- MyBatis Core -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.6</version>
    </dependency>
    <!-- JDBC Driver -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.28</version>
    </dependency>
</dependencies>
 
 
cs

 

2.데이터베이스 설정

MySQL 데이터베이스를 사용하고, mybatis-config.xml 파일에 데이터베이스 연결 정보를 설정합니다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis_example"/>
                <property name="username" value="your_username"/>
                <property name="password" value="your_password"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="UserMapper.xml"/>
    </mappers>
</configuration>
 
 
cs

 

3.SQL 매핑

UserMapper.xml 파일에 SQL 쿼리와 결과 매핑을 정의합니다.

1
2
3
4
5
6
7
8
<?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.example.UserMapper">
    <select id="getAllUsers" resultType="User">
        SELECT * FROM users
    </select>
</mapper>
 
 
cs

 

4.Java 코드

1
2
3
4
5
6
7
8
9
10
package com.example;
 
public class User {
    private int id;
    private String username;
    private String email;
 
    // getters and setters
}
 
cs

 

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
package com.example;
 
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
 
import java.io.IOException;
import java.io.Reader;
import java.util.List;
 
public class Main {
    public static void main(String[] args) {
        String resource = "mybatis-config.xml";
        try (Reader reader = Resources.getResourceAsReader(resource)) {
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
            try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
                UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
                List<User> users = userMapper.getAllUsers();
                for (User user : users) {
                    System.out.println("ID: " + user.getId() + ", Username: " + user.getUsername() + ", Email: " + user.getEmail());
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
 
cs

 

💡JPA 사용 예)

1. 프로젝트 설정

Maven 프로젝트를 생성하고, Spring Boot와 Spring Data JPA 의존성을 추가합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<dependencies>
    <!-- Spring Boot Starter -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <!-- Spring Data JPA -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <!-- H2 Database -->
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
    </dependency>
</dependencies>
 
 
cs

 

2. 엔티티 클래스

User 엔티티 클래스를 생성합니다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.example.demo.entity;
 
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
 
@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String username;
    private String email;
 
    // getters and setters
}
 
 
cs

 

3. Repository 인터페이스

UserRepository라는 Spring Data JPA Repository 인터페이스를 생성합니다.

 

1
2
3
4
5
6
7
8
package com.example.demo.repository;
 
import com.example.demo.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
 
public interface UserRepository extends JpaRepository<User, Long> {
}
 
 
cs

 

 

4 Java 코드

Spring Boot 애플리케이션 클래스와 데이터베이스에 데이터를 추가하고 조회하는 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
package com.example.demo;
 
import com.example.demo.entity.User;
import com.example.demo.repository.UserRepository;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
 
@SpringBootApplication
public class DemoApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
 
    @Bean
    public CommandLineRunner demo(UserRepository repository) {
        return (args) -> {
            // 데이터 추가
            repository.save(new User("alice""alice@example.com"));
            repository.save(new User("bob""bob@example.com"));
 
           
 
 
cs

 

 

💡MyBatis가 적합한 경우

  • 데이터베이스에 대한 세밀한 제어가 필요한 경우.
  • 기존 SQL 코드를 재활용하거나 레거시 데이터베이스와 통합해야 하는 경우.
  • SQL 튜닝 및 성능 최적화가 필요한 경우.

 

💡 JPA가 적합한 경우

  • 객체 중심의 개발이 필요한 경우.
  • 객체 간의 관계를 간편하게 다루어야 하는 경우.
  • CRUD 작업을 자동화하고자 하는 경우.

 

💻결론

MyBatis와 JPA는 각각의 장점과 사용 시나리오에 따라 선택해야 합니다. MyBatis는 SQL에 대한 직접적인 제어를 허용하고, JPA는 객체 중심의 개발과 ORM을 통한 데이터베이스 액세스를 간소화합니다. 개발 프로젝트의 요구 사항과 개발자의 선호도에 따라 적절한 기술을 선택해야 합니다.

반응형

'프로그래밍 > Java' 카테고리의 다른 글

[Java] 컴파일러(Compiler) vs 인터프리터(Interpreter)  (0) 2023.09.29
[Java] 컴파일 과정  (0) 2023.09.28
[Java] JSP와 Servlet  (0) 2023.09.24
[Java] 스택(Stack)과 큐(Queue)  (0) 2023.08.24
[Java] Math함수  (0) 2023.08.17