티스토리 뷰

728x90
반응형

개발 환경

java 21.0.4 2024-07-16 LTSJava(TM) SE Runtime Environment (build 21.0.4+8-LTS-274)

Java HotSpot(TM) 64-Bit Server VM (build 21.0.4+8-LTS-274, mixed mode, sharing)

 

Tomcatv 10.1

EclipseVersion: 2024-06 (4.32.0)Build id: 20240606-1231


프로젝트 구조

애너테이션(annotation)은 프로젝트의 기본 구조를 형성하는데 도움을 준다.

src/main/java
    ├── com
        └── example
            ├── controller
            ├── service
            ├── repository
            ├── model
            ├── mapper
            ├── config
            └── exception
src/main/resources
    ├── mybatis
        └── mybatis-config.xml
    ├── mybatis.mappers
    	└── mybatisMapper.xml
    ├── applicationContext.xml
    └── dispatcherServlet.xml
webapp
    ├── WEB-INF
        └── views
            ├── index.jsp
            ├── dataAccess.jsp
            └── error.jsp

src/main/java 디렉토리

com.example.controller
@Controller 애너테이션이 붙은 클래스들이 위치합니다. 주로 웹 요청을 처리하고 서비스 레이어를 호출합니다.

@Controller
@RequestMapping("/data")
public class DataAccessController {
    private final DataService dataService;

    @Autowired
    public DataAccessController(DataService dataService) {
        this.dataService = dataService;
    }

    @GetMapping("/mybatis")
    public String getData(Model model) {
        List<MemberVO> members = dataService.getAllMembers();
        model.addAttribute("members", members);
        return "dataAccess";
    }
}

com.example.service
@Service 애너테이션이 붙은 클래스들이 위치합니다. 비즈니스 로직을 처리하는 계층입니다.

@Service
public class DataService {
    private final MemberRepository memberRepository;

    @Autowired
    public DataService(MemberRepository memberRepository) {
        this.memberRepository = memberRepository;
    }

    public List<MemberVO> getAllMembers() {
        return memberRepository.selectAllMembers();
    }
}

com.example.repository
@Repository 애너테이션이 붙은 클래스들이 위치하며, MyBatis와의 인터페이스를 정의합니다. 

데이터베이스 작업을 처리하는 계층입니다.

@Repository
public interface MemberRepository {
    List<MemberVO> selectAllMembers();
}

com.example.model

도메인 모델 클래스가 위치하는 곳입니다. 주로 데이터베이스 테이블과 매핑되는 클래스들이 위치합니다.

public class MemberVO {
    private String id;
    private String pwd;

    // Getters and setters
}

com.example.config
Spring과 MyBatis 설정을 위한 자바 기반 설정 클래스 또는 XML 파일들이 위치합니다. 

@Configuration
@EnableTransactionManagement
@MapperScan("com.example.repository")
public class MyBatisConfig {
    @Bean
    public DataSource dataSource() {
        return new PooledDataSource("oracle.jdbc.OracleDriver", "jdbc:oracle:thin:@localhost:1521/xe", "system", "1234");
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        return sessionFactory.getObject();
    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="
           http://www.springframework.org/schema/beans 
           https://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/context 
           https://www.springframework.org/schema/context/spring-context.xsd
           http://www.springframework.org/schema/mvc 
           https://www.springframework.org/schema/mvc/spring-mvc.xsd
           http://www.springframework.org/schema/tx 
           http://www.springframework.org/schema/tx/spring-tx.xsd">
           
   
	<bean> ... </bean>

</beans>

com.example.exception
커스텀 예외 처리를 위한 클래스들이 위치하는 곳입니다.

@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    public String handleException(Model model, Exception e) {
        model.addAttribute("errorMessage", e.getMessage());
        return "error";
    }
}

src/main/resources 디렉터리

MyBatis 관련 XML 파일
mybatis/mappers/MemberMapper.xml: MyBatis에서 사용할 SQL 매퍼 파일이 위치합니다

<?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.blog.mapper.FreeBoardMapper">

	<resultMap type="FreeBoardVO" id="freeBoardResult">
		<result property="seqNo" column="seqNo" />
		<result property="subject" column="subject" />
		<result property="writer" column="writer" />
		<result property="regDate" column="regDate" />
		<result property="contentsText" column="contentsText" />
	</resultMap>

	<select id="allList" resultMap="freeBoardResult">
		select 
			fb.seqNo
		, 	fb.subject
		, 	fb.writer
		, 	fb.regDate
		, 	fb.contentsText 
		from free_board fb
		order by fb.seqNo desc
	</select>
	
	<insert id="create" parameterType="com.blog.model.FreeBoardVO">
		insert into free_board(
			subject
		, 	writer
		, 	contentsText
		) values (
			#{ subject }
		, 	#{ writer }
		, 	#{ contentsText }
		)
	</insert>
	
	<select id="read" parameterType="map" resultMap="freeBoardResult">
		select 
		  	fb.seqNo
		, 	fb.subject
		, 	fb.writer
		, 	fb.regDate
		, 	fb.contentsText 
		from free_board fb
		where fb.seqNo = #{ seqNo } 
	</select>
	
	<update id="update" parameterType="com.blog.model.FreeBoardVO">
		update free_board fb set
			fb.subject = #{ subject }
		,	fb.writer = #{ writer }
		,	fb.contentsText = #{ contentsText }
		where fb.seqNo = #{ seqNo }
	</update>
	
	<delete id="delete" parameterType="map">
		delete free_board fb
		where fb.seqNo = #{ seqNo }
	</delete>

	
</mapper>

MyBatis 설정 파일
mybatis-config.xml: MyBatis 설정을 위한 XML 파일이 위치합니다.

<configuration>
    <typeAliases>
        <typeAlias alias="MemberVO" type="com.example.model.MemberVO" />
    </typeAliases>
</configuration>

applicationContext.xml
Spring의 전역 설정 파일로, MyBatis와 Spring의 연동 설정이 포함됩니다.

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="...">
    <context:component-scan base-package="com.example" />
    <import resource="mybatis-config.xml" />
</beans>

webapp/WEB-INF/views 디렉터리

dataAccess.jsp
컨트롤러에서 전달받은 데이터를 출력하는 역할을 합니다.

<h2>Member List</h2>
<table>
    <tr>
        <th>ID</th>
        <th>Password</th>
    </tr>
    <c:forEach var="member" items="${members}">
        <tr>
            <td>${member.id}</td>
            <td>${member.pwd}</td>
        </tr>
    </c:forEach>
</table>

error.jsp
예외가 발생했을 때 출력되는 오류 페이지입니다.

<h2>Error occurred: ${errorMessage}</h2>

 

추가 정보

스프링 프레임워크(Spring Framework)-기본 애너테이션

 

스프링 프레임워크(Spring Framework)-기본 애너테이션

개발 환경java 21.0.4 2024-07-16 LTSJava(TM) SE Runtime Environment (build 21.0.4+8-LTS-274)Java HotSpot(TM) 64-Bit Server VM (build 21.0.4+8-LTS-274, mixed mode, sharing) Tomcatv 10.1EclipseVersion: 2024-06 (4.32.0)Build id: 20240

jangjeonghun.tistory.com

 

728x90
반응형