1. 이클립스 프로젝트에서 "mybatis"를 검색합니다 .

  •   mybatis Generator1.4.0을 받아줍니다. 

 

 

2. 프로젝트 내부에 적절한 위치에 "Mybatis Generator"를 사용하기위한  xml 파일을 생성해줍니다. 

 

 

3. generatorConfig.xml을 생성 후 아래와 같은 내용을 작성해줍니다. 

 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration PUBLIC
 "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
 "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
	<context id="simple" targetRuntime="MyBatis3simple">
		<jdbcConnection
			connectionURL="URL을 적엉주세요 "
			driverClass="oracle.jdbc.driver.OracleDriver" password="비밀번호"
			userId="아이디" />

		<javaModelGenerator
			targetPackage="com.project.domain"
			targetProject="board/src/main/java">
			<property name="enableSubPackages" value="true" />
			<property name="trimStrings" value="true" />
		</javaModelGenerator>

		<sqlMapGenerator 
			targetPackage="mybatis.mapper"
			targetProject="board/src/main/resources" />

		<javaClientGenerator
			targetPackage="example.mapper" 
			targetProject="board/src/main/java"
			type="XMLMAPPER" />

		<table tableName="usertb" />
		<table tableName="member" />
	</context>
</generatorConfiguration>

 

     3-1.xml 파일을 보시면 tragetRuntime이 있습니다. 이곳을 적절하게 바꿔주시면 다양한 generator를 사용가능 

 

MyBatis Generator Core – MyBatis Generator Quick Start Guide

MyBatis Generator Quick Start Guide MyBatis Generator (MBG) generates code in different styles depending on how it is configured. This is controlled by specifying the targetRuntime attribute on a configuration element. The table below summarizes the differ

mybatis.org

4. RUN MyBatis Generator를 실행해주면 정상적으로 파일이 생성되게 됩니다.

 

 

 

5. 결과 

 

 

 

 

 

 

#mapper 파일이 생성 안되는 경우 

  • targetRunTime의 속성 값을 "MyBatis3Simple" 을 추가 해주시거나 수정해주세요 
<context id="simple" targetRuntime="MyBatis3simple">

 

 

#mybatis "src/main/resources"에 mapper파일 생성 방법 

  • 아래와 같이 "targetPrject"에 "src/main/resources"를 작성해주세요 
		<sqlMapGenerator 
			targetPackage="mybatis.mapper"
			targetProject="board/src/main/resources" />


[ 자바 응용프로그램 개발을 위해 Toad를 이용해 0412Sawon_sql 파일을 만들고 테이블 생성 ]


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
--Sawon 테이블 삭제 
drop table sawon ;
 
--일련번호를 만들어 줄 Sequence 생성 
create sequence sawonseq;
 
 
--Sawon 테이블 생성 
create table sawon ( 
bunho number(10primary key,
name varchar2(50),
email varchar2(100),
tel varchar2(12),
address varchar2(100)
);
 
--시퀀스를 이용한 삽입 
insert into sawon(bunho, name, email, tel, address)
values(sawonseq.nextval, '감강찬','kang@gmail.com','01025458874','고려귀주');
 
insert into sawon(bunho, name, email, tel, address)
values(sawonseq.nextval, '김유신','yousin@gmail.com','01058687434','신라거주');
 
insert into sawon(bunho, name, email, tel, address)
values(sawonseq.nextval, '근초고왕','chgo@gmail.com','01021545785','백제거주');
 
insert into sawon(bunho, name, email, tel, address)
values(sawonseq.nextval, '을지문덕','ul@gmail.com','01025458874','고구려살수');
 
insert into sawon(bunho, name, email, tel, address)
values(sawonseq.nextval, '무열왕','mu@gmail.com','01025458874','신라');
 
--데이터 삽입 확인 
select * from sawon;
 
--address에 신라가 포함된 데이터만 검색 
select * from sawon
where address like '%라';
 
--번호를 가지고 이름과 이메일 전화번호와 주소를 변경 
update sawon
set name='을지문덕', email='ulul@naver.com', tel='01052458774', address='고구려살수'
where bunho=4;
 
--번호를 가지고 삭제 
delete sawon where bunho=4;
 
--데이터베이스에 저장 
commit;
 
rollback
cs



2. Simple Spring Maven Project를 생성 

3. java Version과 Spring Version 변경 


4. 저장소 설정 


1
2
3
4
5
6
<repositories>
    <repository>
        <id>codelds</id>
        <url>https://code.lds.org/nexus/content/groups/main-repo</url>
    </repository>
</repositories>
cs


5.의존성 설정 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 
<dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc6</artifactId>
            <version>11.2.0.3</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring-framework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.2</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.1</version>
        </dependency>
 
cs


5. 테이블과 연동할 Vo 클래스를 생성 (com.tistory.tstigma.domain.Sawon)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
 
 
package com.tistory.tstigma.domain;
 
public class Sawon {
 
    private String bunho ;
    private String name ;
    private String email; 
    private String tel;
    private String address;
    public String getBunho() {
        return bunho;
    }
    public void setBunho(String bunho) {
        this.bunho = bunho;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getTel() {
        return tel;
    }
    public void setTel(String tel) {
        this.tel = tel;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    
    @Override
    public String toString() {
        return "Sawon [bunho=" + bunho + ", name=" + name + ", email=" + email + ", tel=" + tel + ", address=" + address
                + "]";
    }
}
 
cs


[ xml 파일에 sql을 작성할 때 사용하는 MyBatis 환경 설정 파일을 생성 ]

=> src/main/resources 디렉토리에 mybatis-config.xml 

=> VO  클래스들이 모여있는 패키지 이름을 등록해서 mapper파일에서 패키지 이름을 입력하지 않아도 되도록 설정 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?xml version="1.0" encoding="UTF-8"?>
 
<!DOCTYPE configuration
 
    PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
 
    "http://mybatis.org/dtd/mybatis-3-config.dtd">
 
 
 
<configuration>
 
    <typeAliases>
 
        <package name="com.tistory.tstigma" />
 
    </typeAliases>
 
</configuration>
 
cs




7. sql을 작성할 mapper파일을 생성 

=> src/main/resource 디렉토리 안에 mapper 디렉토리를 생성하고 그 안에 sawon.xml 파일로 생성 



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
<?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="sawon">
 
 
 
    <!-- sawon 테이블의 전체 데이터를 가져오는 sql -->
 
    <!-- result Type은 sawon만 써주면 된다 결과 -->
 
    <select resultType="Sawon" id ="AllSawon" >
 
        select bunho, name, email, tel, address 
 
        from sawon; 
 
    </select>
 
 
 
    <!-- sawon 테이블에 데이터를 저장하는 sql  -->
 
    <!-- insert update delete는 결과가 없다.  -->
 
    <!-- parameter는 #같은 반인딩 해줄 때 사용  -->
 
    <insert  parameterType="Sawon" id="insertsawon">
 
            insert into sawon (bunho, name, email, tel, address) 
 
            values(sawonseq.nextval, #{name}, #{email},#{address})
 
    </insert>
 
    
 
    <!-- sawon 테이블에서 bunho를  가지고 일치하는 데이터의 name, email, tel, address를 수정하는 sql  -->
 
    <update id="updatesawon" parameterType="Sawon">
 
        update sawon 
 
        set name=#{name}, email=#{email}, address=#{address}
 
        where bunho=#{bunho}
 
    </update>
 
    
 
    <!-- sawon 테이블에서 bunho를 가지고 삭제하는 sql  -->
 
    <delete id="deletesawon" parameterType="java.lang.Integer">
 
        delete sawon where bunho=#{bunho}
 
    </delete>
 
    
 
    
 
    <!-- 테이블에서 name을 포함한 검색  -->
 
    <!--  굳이 ?  -->
 
    
 
    <select id="getsawon" parameterType="java.lang.String" resultType="Sawon">
 
        select bunho, name, email, tel, address
 
        from sawon
 
        where lower(trim(name)) like '%' || #{name} || '%'
 
    </select>
 
    
 
</mapper>
cs



8. mapper 파일에 있는 Sql 을 호출하는 Dao 클래스를 만들고 메소드를 작성 

=>com.tstigma.tistory.dao.SawonDao



9. 프로젝트에 Spring 설정 파일을 추가하고 bean(spring이 생성해주는 객체 )을 생성하는 코드를 작성 

=> src/ main/resources 디렉토리에 applicationContext.xml


1)context 네임 스페이스 추가 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
<?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: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.1.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">
 
 
 
 
 
 
 
     <!-- 어노테이션을 프로젝트에서 사용할 수있도록 설정   -->
 
    <context:annotation-config/>
 
    
 
    <!-- 패키지 안에 있는 클래스들 중에서 어노테이션이 붙은 클래스들의 bean을 자동 생성해주는 설정  -->
 
    <context:component-scan base-package="com.tistory.tstigma"></context:component-scan>
 
    
 
    <!-- 데이터 베이스 접속 정보를 저장 DataSource 클래스의 bean -->
 
    <bean id="dataSource"
 
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
 
    <!-- 접속할 데이터베이스 종류  -->
 
        <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
 
        <property name="url" value="jdbc:oracle:thin:@192.168.0.200:1521:xe"/>
 
        <property name="username" value="user08"/>
 
        <property name="password" value="user08"/>
 
    </bean>
 
 
 
    <!-- myBatis 사용을 위한 Bean -->
 
    <!-- 공장이기 때문에 이 팩토리에게 무엇인가 하나더 만들어주세요 요청해야합니다. 
 
    그 주는 것은 아래 실제 운영으 위한 mybatis 클래스의 빈을 추가  -->
 
    <bean class="org.mybatis.spring.SqlSessionFactoryBean" id ="sqlSessionFactory">
 
        <property name="dataSource" ref="dataSource"/>
 
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
 
        <property name="mapperLocations" value="classpath:mappers/sawon.xml"/>
 
    </bean>
 
 
 
 
 
    <!-- 실제 mybatis 운영을 위한 클래스의 bean -->
 
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
 
        <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory" />
 
    </bean>
 
 
 
    
 
 
 
</beans>
cs


10. main 메소드를 소유한 Main 클래스를 만들어서 spring 설정 파일의 내용을 읽는 코드를 작성 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
        GenericXmlApplicationContext context = 
            new GenericXmlApplicationContext(
                "classpath:applicationContext.xml");
        SawonDao dao = context.getBean(SawonDao.class);
 
 
        //데이터 조회 
        System.out.println(dao.allsawon());
 
        //데이터 수정
        Sawon sawon = new Sawon();
        sawon.setBunho(4);
        sawon.setName("배수지");
        sawon.setEmail("bae@gmail.com");
        sawon.setTel("011");
        sawon.setAddress("광주");
        dao.updatesawon(sawon);
        //문자열을 가지고 조회할 때는 trim() 과 대소문자 변환을 포함
        System.out.println(dao.getsawon("수".toLowerCase()));
cs


+ Recent posts