1. 프로젝트 생성
2. 기본 설정
1) Spring Config
package com.oracle.oBootMybatis01.configration;
import javax.persistence.EntityManager;
import javax.sql.DataSource;
import org.springframework.context.annotation.Configuration;
@Configuration
public class SpringConfig {
private EntityManager em;
private DataSource dataSource;
public SpringConfig(EntityManager em, DataSource dataSource) {
this.em = em;
this.dataSource = dataSource;
}
}
[오류1]
Parameter 1 of constructor in com.oracle.oBootMybatis01.configration.SpringConfig required a bean of type 'javax.activation.DataSource' that could not be found.
-> import javax.activation.DataSource; 이 아니라 import javax.sql.DataSource;를 임포트 해야함.
2) application.yml
server:
port: 8386
# Oracle Connect
spring:
datasource:
driver-class-name: oracle.jdbc.driver.OracleDriver
url: jdbc:oracle:thin:@localhost:1521/xe
username: scott
password: tiger
#ORM JPA
jpa:
hibernate:
ddl-auto: none
properties:
hibernate:
show_sql: true
format_sql: true
#view resolver(Templete -> jsp use)
mvc:
view:
prefix: /WEB-INF/views/
suffix: .jsp
#Mybatis
mybatis:
# dto Location
# type-aliases-package: com.oracle.oBootMybatis01.model
# xml Location
config-location: classpath:configuration.xml
mapper-locations: classpath:mappers/*.xml
* config-location: classpath:configuration.xml
* mapper-location: classpath:mappers/*.xml -> mappers 폴더 안에 있는 모든 파일들
[에러2] Failed to configure a DataSource
-> Database에 연결할 때 필요한 정보가 없기 때문에, 어플리케이션 실행에 실패했다.
application.properties 혹은 appliction.yml 파일 확인하기
-> Mybatis01-> MyBatis01로 되어 있음
4. 게시판 리스트 불러오기
1) controller
package com.oracle.oBootMybatis01.controller;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.oracle.oBootMybatis01.model.Emp;
import com.oracle.oBootMybatis01.service.EmpService;
import com.oracle.oBootMybatis01.service.Paging;
@Controller
public class EmpController {
private static final Logger logger = LoggerFactory.getLogger(EmpController.class);
@Autowired
private EmpService es;
@RequestMapping(value = "list")
public String list(Emp emp, String currentPage, Model model) {
logger.info("컨트롤러 list 시작");
int total = es.total();
System.out.println("컨트롤러 list total : " + total);
Paging pg = new Paging(total, currentPage);
emp.setStart(pg.getStart());
emp.setEnd(pg.getEnd());
List<Emp> listEmp = es.listEmp(emp);
System.out.println("Emp 컨트롤러 list listEmp.size() : " + listEmp.size());
model.addAttribute("listEmp", listEmp);
model.addAttribute("pg", pg);
model.addAttribute("total", total);
return "list";
}
}
2) 게시글 총 갯수 구하기
- es.total();
@Service
public class EmpServiceImpl implements EmpService {
@Autowired
private EmpDao ed;
@Override
public int total() {
System.out.println("Emp total 서비스 시작");
int totCnt = ed.total();
return totCnt;
}
}
3) ed.total();
@Repository
public class EmpDaoImpl implements EmpDao {
@Autowired
private SqlSession session;
@Override
public int total() {
int totCnt = 0;
System.out.println("EmpDao total 시작");
try {
totCnt = session.selectOne("mjTotalEmp");
System.out.println("EmpDao totCnt : " + totCnt);
} catch (Exception e) {
System.out.println("EmpDao Error : " + e.getMessage());
}
return totCnt;
}
}
4) totCnt = session.selectOne("mjTotalEmp");
<?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.oracle.oBootMybatis01.EmpMapper">
<select id="mjTotalEmp" resultType="int">
select count(*) from emp
</select>
</mapper>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<typeAlias alias="Emp" type="com.oracle.oBootMybatis01.model.Emp"/>
</typeAliases>
</configuration>
** SqlSession
: mapper.xml 에 등록된 sql 문을 실행하고 트랜잭션을 관리
selectOne | select 문이 실행된 하나의 객체를 리턴한다. |
selectList | select 문이 실행되어 여러개의 객체가 담긴 리스트를 리턴 |
selectMap | 결과 목록이 Map으로 변환되어 리턴 |
insert | insert 문이 실행 |
update | update 문이 실행 |
delete | delete 문이 실행 |
package com.oracle.oBootMybatis01.service;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class Paging {
private int currentPage = 1;
private int rowPage = 10;
private int pageBlock = 10;
private int start;
private int end;
private int startPage;
private int endPage;
private int total;
private int totalPage;
public Paging(int total, String currentPage1) {
//예) total = 123 currentPage = 2
this.total = total;
if(currentPage1 != null) {
this.currentPage = Integer.parseInt(currentPage1);
}
start = (currentPage - 1) * rowPage + 1; //1* 10 + 1 = 11
end = start + rowPage - 1; //11+10 + 1 = 20
totalPage = (int)Math.ceil((double)total/rowPage); // 123/10 = 13
startPage = currentPage - (currentPage - 1 ) % pageBlock;
endPage = startPage + pageBlock - 1;
if(endPage > totalPage ) {
endPage = totalPage;
}
}
}
@Override
public List<Emp> listEmp(Emp emp) {
List<Emp> empList = null;
System.out.println("Emp listEmp 서비스 시작");
empList = ed.listEmp(emp);
System.out.println("Emp listEmp 서비스 empList.size() : " + empList.size());
return empList;
}
@Override
public List<Emp> listEmp(Emp emp) {
List<Emp> empList = null;
try {
empList = session.selectList("mjEmpListAll3", emp);
} catch (Exception e) {
System.out.println("EmpDaoImpl listEmp Exception : " + e.getMessage());
}
return empList;
}
* parameter는 #{}으로 사용
<select id="mjEmpListAll" parameterType="Emp" resultType="Emp">
SELECT *
FROM (
SELECT rownum rn, a.*
FROM (SELECT * FROM emp ORDER BY empno) a
)
WHERE rn BETWEEN #{start} AND #{end}
</select>
[오류3] Whitelabel Error Page
-> Spring Boot에서 내장된 Tomcat을 사용하는 경우 jsp를 처리하는 서블릿을 추가하지 않아 발생하는 것으로 pom.xml에 아래와 같이 추가해준다
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
* Mybatis의 기본 구조를 이해해보자 *
controller -> sevice -> dao -> session에 mapping 된 sql 문 실행
'IT > SpringDay' 카테고리의 다른 글
Mybatis③ - mailSender (0) | 2022.05.30 |
---|---|
Mybatis② (0) | 2022.05.30 |
06.JpaApi② (0) | 2022.05.24 |
06.JpaApi① (0) | 2022.05.22 |
05.JPA02② (0) | 2022.05.19 |