Spring - mybatis

2020. 9. 1. 17:39Java/Spring

반응형

- Spring Framework에서 제공하는 JDBC 라이브러리를 보다 쉽게 작업할 수 있도록 만든 라이브러리

- Mapper의 역할을 확장하여 쿼리문 작성을 모두 Mapper에서 할 수 있도록 지원한다.

 

 

1. 라이브러리 추가하기

https://mvnrepository.com/search?q=mybatis

 

Maven Repository: mybatis

An enhanced toolkit of Mybatis to simplify development. Last Release on Aug 23, 2020

mvnrepository.com

mybatis를 선택하여 아래 두개의 최신버전의 dependency를 복사하여 pom.xml에 추가한다.

추가한 전체 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>cookingcoding</groupId>
	<artifactId>mybatis</artifactId>
	<version>0.0.1-SNAPSHOT</version>



	<!-- xml에서 사용할 속성들 -->
	<properties>
		<!-- 자바버전 -->
		<java-version>1.8</java-version>
		<!-- 스프링 버전 -->
		<org.springframework-version>5.1.9.RELEASE</org.springframework-version>
		<!-- <org.springframework-version>4.3.25.RELEASE</org.springframework-version> -->
		<org.slfrj-version>1.7.26</org.slfrj-version>
		<ch.qos.logback-version>1.2.3</ch.qos.logback-version>
		<javax.annotation-version>1.3.2</javax.annotation-version>
		<org.aspectj-version>1.9.6</org.aspectj-version>
		<mysql-version>8.0.21</mysql-version>
		<org.apache.commons-version>2.7.0</org.apache.commons-version>
		<org.mybatis-version>3.5.5</org.mybatis-version>
		<mybatis-spring-version>2.0.5</mybatis-spring-version>
	</properties>


	<dependencies>
		<!-- spring-context -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>

		<!-- slf4j -->
		<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${org.slfrj-version}</version>
		</dependency>
		<!-- logback -->
		<!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-classic -->
		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-classic</artifactId>
			<version>${ch.qos.logback-version}</version>
			<exclusions>
				<exclusion>
					<groupId>org.slf4j</groupId>
					<artifactId>slf4j-api</artifactId>
				</exclusion>
			</exclusions>
			<scope>runtime</scope>
		</dependency>
		<!-- https://mvnrepository.com/artifact/javax.annotation/javax.annotation-api -->
		<dependency>
			<groupId>javax.annotation</groupId>
			<artifactId>javax.annotation-api</artifactId>
			<version>${javax.annotation-version}</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>${org.aspectj-version}</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>${mysql-version}</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-dbcp2 -->
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-dbcp2</artifactId>
			<version>${org.apache.commons-version}</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>${org.mybatis-version}</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>${mybatis-spring-version}</version>
		</dependency>


	</dependencies>
</project>

2. beanConfigClass 세팅 

JdbcTemplate를 사용하지 않고 SqlSessionFactory,MapperFactoryBean을 사용하므로 새로 설정해준다.

 

@Configuration
@ComponentScan(basePackages = "cookingcoding.beans")
public class beanConfigClass {

	
	@Bean
	public BasicDataSource source() {
		BasicDataSource source = new BasicDataSource();
		source.setDriverClassName("com.mysql.cj.jdbc.Driver");
		source.setUrl("jdbc:mysql://localhost/spring_study?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&validationQuery=select 1&characterEncoding=UTF-8");
		source.setUsername("root");
		source.setPassword("ggthegame2");
		return source;
	}
	//sqlSessionFactory : jdbc를 처리하는 객체
	@Bean
	public SqlSessionFactory factory(BasicDataSource source) throws Exception {
		SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
		factoryBean.setDataSource(source);
		SqlSessionFactory factory = factoryBean.getObject();
		return factory;
	}
	
	@Bean
	public MapperFactoryBean<MapperInterface> test_mapper(SqlSessionFactory factory) throws Exception{
		MapperFactoryBean<MapperInterface> factoryBean = new MapperFactoryBean<MapperInterface>(MapperInterface.class);
		factoryBean.setSqlSessionFactory(factory);
		return factoryBean;
	}

}

 

 

 


3. MapperInterface 생성 및 sql 작성

 

MapperInterface 를 생성해준다.

 

mybatis에서는 MapperInterface에 sql 구문을 작성하게 된다.

 

public interface MapperInterface {
	
	@Results({
		@Result(column = "numarea", property="numarea"),
		@Result(column = "chararea", property="chararea")
	})
	@Select("Select * from springjdbc")
	List<JdbcBean> select_data();
	
	@Insert("insert into springjdbc (numarea,chararea) values (#{numarea},#{chararea})")
	void insert_data(JdbcBean bean);
	
	@Update("update springjdbc set chararea = #{chararea} where numarea = #{numarea}")
	void update_data(JdbcBean bean);
	
	@Delete("delete from springjdbc where numarea = #{anythig}") //매개변수 데이터가 일반 변수로 하나이면 아무거나 적어도 자동으로 주입 됨
	void delete_data(int data1);
}

@Results의 설정은 Database의 column명과 databean의 객체 이름이 다를 경우 설정해주고 같을 경우에는 자동으로 주입되므로 생략 가능하다.

 

 

위 인테페이스의 메소드를 메인에서 실행하면 sql 구문이 실행되고 정상 적용 된다.

public class MainClass {

	public static void main(String[] args) {
		AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(beanConfigClass.class);

		MapperInterface mapper = ctx.getBean("test_mapper",MapperInterface.class);
		
		JdbcBean bean1 = new JdbcBean();
		bean1.setNumarea(3);
		bean1.setChararea("세번째");
		
		mapper.insert_data(bean1);
		mapper.delete_data(3);
		bean1.setNumarea(2);
		bean1.setChararea("수정된 두번째");
		mapper.update_data(bean1);
		List<JdbcBean> list1 = mapper.select_data();
		
		for(JdbcBean li : list1) {
			System.out.println("numarea =>"+li.getNumarea());
			System.out.println("chararea =>"+li.getChararea());
		}
		
		ctx.close();
	}

}

 

반응형

'Java > Spring' 카테고리의 다른 글

Spring(MVC) - 기본세팅(2) - XML  (0) 2020.09.03
Spring(MVC) - 기본세팅(1)  (0) 2020.09.02
Spring - JDBC(mysql)  (0) 2020.09.01
Spring - @AspectJ  (0) 2020.08.31
Spring - execution 사용법  (0) 2020.08.30