스프링과 myBatis
ORM(Object Relational Mapping) 프레임워크는 데이터베이스와 객체와의 관계를 맵핑시켜 퍼시스턴스 로직 처리를 도와주는 프레임워크이다.
대표적으로 MyBatis와 hibernate, JPA가 있다
myBatis는 SQL쿼리문, 예외처리, 트랙잭션 관리들을 XML형식으로 관리한다.
POJO(Plain Old Java Object)객체와 테이블의 컬럼들을 편리하고 빠르고 정확하게 매칭할 수 있다.
myBatis의 목표와 특징은 쉽고, 간단하고, 의존성이 적다는 것이다
SQL문과 자바코드를 분리함으로 인해 자바 개발자는 쿼리문을 신경 쓰지 않아도 된다.
myBatis는 자바오브젝트와 SQL문 사이의 자동 매핑 기능을 지원하는 ORM 프레임워크이다
자바코드와 SQL를 분리하므로서 SQL문의 변경이 있을 때 마다 자바를 수정하지 않아도 되고 컴파일을 하지 않아도 된다
[실습]
Project : Chapter05_XML
Packagge : user.dao
Interface : UserDAO.java
Class : UserDAOMybatis.java
src/main/resources
Folder : spring
File : applicationContext.xml
mybatis-config.xml
db.properties
Folder : mapper
File : userMapper.xml
[ Chapter05_XML ]
legacy - configuration - convet to maven - pom.xml(17)
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>Chapter05_XML</groupId>
<artifactId>Chapter05_XML</artifactId>
<version>0.0.1-SNAPSHOT</version>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<release>17</release>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.37</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.30</version>
<scope>provided</scope>
</dependency>
<!-- Connection Pool -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.37</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.4</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.11.0</version>
</dependency>
<!-- MySQL -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.3.0</version>
</dependency>
</dependencies>
</project>
<!-- MyBatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.16</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>3.0.3</version>
</dependency>
user.bean
user.service
user.main
다 똑같다.
user.dao
UserDAO.java
user.dao.impl
UserMybatisDAO.java로 바꾼다.
UserMybatisDAO.java
package user.dao.impl;
import java.util.List;
import user.bean.UserDTO;
import user.dao.UserDAO;
public class UserMybatisDAO implements UserDAO {
@Override
public void write(UserDTO userDTO) {
// TODO Auto-generated method stub
}
@Override
public List<UserDTO> getUserList() {
// TODO Auto-generated method stub
return null;
}
@Override
public UserDTO getExistId(String id) {
// TODO Auto-generated method stub
return null;
}
@Override
public void update(UserDTO userDTO) {
// TODO Auto-generated method stub
}
@Override
public void delete(String id) {
// TODO Auto-generated method stub
}
}
src
spring
applicationContext.xml
db.properties
mybatis-config.xml
sql
usertable.sql
mapper
userMapper.xml
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<typeAlias type="user.bean.UserDTO" alias="user"/>
</typeAliases>
</configuration>
userMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="userSQL"></mapper>
applicationContext.xml
- 전에 만들어놨던 부분
<!-- Connection Pool & Data Source -->
<context:property-placeholder location="classpath:spring/db.properties"/>
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
- 추가된 부분
SqlSessionFactory가 있어줘야 SqlSession가 만들어진다.
<!-- SqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:spring/mybatis-config.xml" />
<property name="mapperLocations" value="classpath:mapper/userMapper.xml"></property>
</bean>
<!-- SqlSession -->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg ref="sqlSessionFactory" />
</bean>
<!-- Transaction -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<constructor-arg ref="dataSource" />
</bean>
UserMybatisDAO.java
@Transactional 추가하기 -- 자동 commit & close
맨 위에 한 번 적어주거나 각 메서드마다 적어줘야한다.
package user.dao.impl;
import java.util.List;
import javax.transaction.Transactional;
import user.bean.UserDTO;
import user.dao.UserDAO;
@Transactional
public class UserMybatisDAO implements UserDAO {
@Override
public void write(UserDTO userDTO) {
// TODO Auto-generated method stub
}
@Override
public List<UserDTO> getUserList() {
// TODO Auto-generated method stub
return null;
}
@Override
public UserDTO getExistId(String id) {
// TODO Auto-generated method stub
return null;
}
@Override
public void update(UserDTO userDTO) {
// TODO Auto-generated method stub
}
@Override
public void delete(String id) {
// TODO Auto-generated method stub
}
}
applicationContext.xml
<bean id="userMybatisDAO" class="user.dao.impl.UserMybatisDAO">
<property name="sqlSession" ref="sqlSession" />
</bean>
<property name="userDAO" ref="userDAOImpl" />로 되어있는거
<property name="userDAO" ref="userMybatisDAO" />로 전부 수정하기
<bean id="userInsertService" class="user.service.UserInsertService" scope="prototype">
<property name="userDTO" ref="userDTO" />
<property name="userDAO" ref="userMybatisDAO" />
</bean>
UserMybatisDAO.java
package user.dao.impl;
import java.util.List;
import javax.transaction.Transactional;
import org.apache.ibatis.session.SqlSession;
import org.springframework.transaction.TransactionManager;
import lombok.Setter;
import user.bean.UserDTO;
import user.dao.UserDAO;
@Transactional
public class UserMybatisDAO implements UserDAO {
@Setter
private SqlSession sqlSession;
@Override
public void write(UserDTO userDTO) {
sqlSession.insert("userSQL.write", userDTO);
}
@Override
public List<UserDTO> getUserList() {
return sqlSession.selectList("userSQL.getUserList");
}
@Override
public UserDTO getExistId(String id) {
return sqlSession.selectOne("userSQL.getExistId", id);
}
@Override
public void update(UserDTO userDTO) {
sqlSession.update("userSQL.update", userDTO);
}
@Override
public void delete(String id) {
sqlSession.delete("userSQL.delete", id);
}
}
userMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="userSQL">
<insert id="write" parameterType="user">
INSERT INTO usertable (name, id, pwd)
VALUES (#{name}, #{id}, #{pwd});
</insert>
<select id="getUserList" resultType="user">
SELECT * FROM usertable;
</select>
<select id="getExistId" parameterType="String" resultType="user">
SELECT * FROM usertable WHERE id = #{id};
</select>
<update id="update" parameterType="user.bean.UserDTO">
UPDATE usertable
SET name = #{name}, pwd = #{pwd}
WHERE id = #{id};
</update>
<delete id="delete" parameterType="String">
DELETE FROM usertable WHERE id = #{id};
</delete>
</mapper>
************** 마이바티스로 다 바뀜 **************
[ Chapter05_ANNO]
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>Chapter05_ANNO</groupId>
<artifactId>Chapter05_ANNO</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.37</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.30</version>
<scope>provided</scope>
</dependency>
<!-- Connection Pool -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.37</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.4</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.11.0</version>
</dependency>
<!-- MySQL -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.3.0</version>
</dependency>
<!-- MyBatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.16</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>3.0.3</version>
</dependency>
</dependencies>
</project>
applicationContext.xml
복붙했기 때문에 원래 있던 코드들을 하나하나 지우는 작업을 할 것이다.
<!-- Connection Pool & Data Source -->
<context:property-placeholder location="classpath:spring/db.properties"/>
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
위에 코드 제거하기
<context:component-scan base-package="spring.conf" />
다 바꾸기
SpringConfiguraion.java
package spring.conf;
import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableTransactionManagement
@PropertySource("classpath:spring/db.properties")
public class SpringConfiguration {
private @Value("${jdbc.driver}") String driver;
private @Value("${jdbc.url}") String url;
private @Value("${jdbc.username}") String username;
private @Value("${jdbc.password}") String password;
@Bean
public BasicDataSource dataSource() {
BasicDataSource basicDataSource = new BasicDataSource();
basicDataSource.setDriverClassName(driver);
basicDataSource.setUrl(url);
basicDataSource.setUsername(username);
basicDataSource.setPassword(password);
return basicDataSource;
}
@Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource());
sqlSessionFactoryBean.setConfigLocation(new ClassPathResource("spring/mybatis-config.xml"));
sqlSessionFactoryBean.setMapperLocations(new ClassPathResource("mapper/userMapper.xml"));
return sqlSessionFactoryBean.getObject(); // SqlSessionFactory 변환 역할
}
@Bean
public SqlSessionTemplate sqlSession() throws Exception{
SqlSessionTemplate sqlSessionTemplate = new SqlSessionTemplate(sqlSessionFactory());
return sqlSessionTemplate;
}
@Bean
public DataSourceTransactionManager transactionManager(){
DataSourceTransactionManager dataSourceTransactionManager =
new DataSourceTransactionManager(dataSource());
return dataSourceTransactionManager;
}
}
UserDTO.java -- @Component
package user.bean;
import org.springframework.stereotype.Component;
import lombok.Getter;
import lombok.Setter;
@Component
@Setter
@Getter
public class UserDTO {
private String name;
private String id;
private String pwd;
public String toString() {
return name + "\t" + id + "\t" + pwd;
}
}
UserMybatisDAO.java -- @Autowired / @Repository
@Repository
@Transactional
public class UserMybatisDAO implements UserDAO {
@Autowired
private SqlSession sqlSession;
HelloSpring.java - @Component
@Component
public class HelloSpring {
@Service
@Autowired
UserInsertService.java
@Service
public class UserInsertService implements UserService {
@Autowired
private UserDTO userDTO;
@Autowired
private UserDAO userDAO;
UserSelectService.java
@Service
public class UserSelectService implements UserService {
@Autowired
private UserDAO userDAO;
UserUpdateService.java
@Service
public class UserUpdateService implements UserService {
@Autowired
private UserDTO userDTO;
@Autowired
private UserDAO userDAO;
UserDeleteService.java
@Service
public class UserDeleteService implements UserService {
@Autowired
private UserDAO userDAO;
applicaionContext.xml
<tx:annotation-driven transaction-manager="transactionManager"/>
→ 자동으로 commit과 close를 한다는 것을 알려줘야한다.
<?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:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<tx:annotation-driven transaction-manager="transactionManager"/>
<context:component-scan base-package="spring.conf" />
<context:component-scan base-package="user.main" />
<context:component-scan base-package="user.bean" />
<context:component-scan base-package="user.dao" />
<context:component-scan base-package="user.sevice" />
</beans>
위에 저 코드를 적거나
다른 방법으로는 SpringConfiguration.java에 어노테이션으로 @EnableTransactionManagement 적어주면 된다.
@Configuration
@EnableTransactionManagement
@PropertySource("classpath:spring/db.properties")
public class SpringConfiguration {
둘이 같은 의미 !!
'Spring' 카테고리의 다른 글
DAY 66 - 스프링 프레임워크 MVC- 회원가입 / 회원목록 / 회원정보수정 (2024.10.10) (1) | 2024.10.10 |
---|---|
DAY 65 - 스프링 프레임워크 - MVC (2024.10.08) (0) | 2024.10.08 |
DAY 64 - 스프링 프레임워크 MVC (2024.10.07) (0) | 2024.10.07 |
DAY 63 - 스프링 프레임워크 - JDBC / HOMEWORK (2024.10.04) (2024.10.07) (1) | 2024.10.04 |
DAY 63 - 스프링 프레임워크 - AOP (2024.10.04) (0) | 2024.10.04 |