DataSource
- 데이터베이스와의 연결을 관리하는 객체
- 데이터베이스 접속 정보를 중앙에서 관리
- 데이터베이스 연결 설정을 외부화하여 애플리케이션의 코드와 분리
Mapper
- SQL 쿼리를 매핑하는 인터페이스나 XML 파일
- 객체지향 프로그래밍 언어인 자바와 관계형 데이터베이스 사이의 매핑을 돕는 프레임워크
@MapperScan("com.example.mapper") - Mapper 인터페이스가 있는 패키지를 스캔
동작 방식
1. MybatisBookRepository 인터페이스의 메서드가 호출될 때 MyBatis는 XML 파일에서 해당 메서드 이름과 일치하는 id를 가진 SQL 쿼리를 찾아 실행합니다.
2. 예를 들어, MybatisBookRepository 인터페이스에서 findAll 메서드를 호출하면 MyBatis는 books.xml 파일에서 id="findAll"을 가진 select 문을 찾아 실행하고 결과를 반환합니다.
3. namespace는 매퍼 인터페이스와 XML 파일을 연결하는 데 사용되며, 메서드 이름과 id 속성은 개별 SQL 쿼리와 매핑됩니다.
MyBatis에서 XML 매퍼 파일(books.xml)과 매퍼 인터페이스(MybatisBookRepository)를 연결하기 위해 XML 파일의 namespace와 매퍼 인터페이스의 패키지 및 인터페이스 이름을 통해 둘을 연결한다.
- XML 매퍼 파일의 namespace는 매퍼 인터페이스의 완전한 이름(패키지명 포함)과 일치해야 한다.
- 매퍼 인터페이스의 메서드 이름과 XML 매퍼 파일의 id 속성 값이 일치해야 한다.
<mapper namespace="com.example.bookmybatis.repository.MybatisBookRepository">
<select id="findAll" resultType="BookEntity">
select
*
from
book
</select>
parameterType이나 resultType에서 클래스의 전체 이름(패키지를 포함한 이름)을 적어야 하는데 위처럼 간단히 적기 위해 application.properties 라는 MyBatis 전체 설정 파일에서 typeAlias를 설정했다.
<configuration>
<typeAliases>
<typeAlias alias="BookEntity" type="com.example.bookmybatis.entity.BookEntity" />
</typeAliases>
</configuration>
@Getter @Setter
@Entity(name="book") // JPA 엔터티임을 나타냄, 데이터베이스 테이블과 매핑
public class BookEntity{
@Id // 기본키
@GeneratedValue(strategy = GenerationType.IDENTITY) // 자동 생성
private Long id;
@Column // 데이터베이스의 열과 매핑됨
private String name;
@Column
private String publisher;
@Column
private int price;
}
여기서 의문점? -- JPA는 ORM방식, MyBatis는 SQL 매핑 방식인데 어떻게 공존하지....?
- 둘이 같이 쓸 수 있다!
- JPA를 사용하여 데이터베이스 테이블 구조를 정의/관리하면서 MyBatis를 사용하여 직접 SQL 쿼리를 제어한다.
MyBatis와 JPA의 연결
- @Entity를 사용하여 데이터베이스 테이블 구조를 정의하고, 이를 통해 데이터베이스 스키마를 관리할 수 있습니다.
- MyBatis를 사용하여 복잡한 쿼리를 처리하고 성능을 최적화할 수 있습니다.
값 동적으로 처리 시 기호 사용 비교
1. Controller(핸들러 메서드) - URL 경로에서 {bookID} 추출하여 bookID 변수에 매핑, 매개변수로 전달
@GetMapping("/books/{bookId}/update")
public String getBookUpdateForm(@PathVariable("bookId") Long bookId, Model model) {
System.out.println("getBookUpdateForm 함수 진입");
BookEntity bookEntity = bookService.getBookById(bookId);
model.addAttribute("book", bookEntity);
System.out.println("model 추가 후");
return "books/updateBookForm";
}
2. XML 매핑 파일(MyBatis 매개변수 표기법)
<select id="findCond" parameterType="BookEntity" resultType="BookEntity">
select
*
from
book
where name like concat('%',#{name}, '%')
and publisher like concat('%',#{publisher}, '%');
</select>
3. html (Thymeleaf 템플릿 엔진 문법)
<tr th:each="book : ${books}">
<td th:text="${book.id}"></td>
<td th:text="${book.name}"></td>
<td th:text="${book.publisher}"></td>
<td th:text="${book.price}"></td>
<td><a th:href="@{/books/{id}/update(id = ${book.id})}">수정</a></td>
<td><a th:href="@{/books/{id}/delete(id = ${book.id})}">삭제</a></td>
</tr>
https://zamezzz.tistory.com/308
https://logical-code.tistory.com/25#google_vignette
이 글은 chatGPT와 함께 작성하였습니다.
'Spring' 카테고리의 다른 글
[Spring] @Lookup - DL(의존관계 조회/탐색) (0) | 2024.08.25 |
---|---|
[Spring] 객체 지향 프로그래밍의 특징과 좋은 객체 지향 설계의 원칙 5가지, SOLID (0) | 2024.08.17 |
[Spring] Intellij 단축키 모음 (-ing) (0) | 2024.06.26 |
[Spring] JPA, Hibernate, Spring data JPA (1) | 2024.06.11 |
[Spring] 'return + view명', 'redirect:/주소' 차이 (0) | 2024.05.14 |