728x90

MyBatis는 iBATIS의 새로운 버전으로 국내에서 가장 많이 사용되는 ORM Framework[각주:1] 중 하나이다. MyBatis는 문서화가 잘 되어 있다고 하지만 막상 실전에 적용시키기에는 이전 버전인 iBATIS에 비해 예제가 부족한 듯하여 자료 정리겸 레퍼런스를 만들어 볼까 한다.

우선 MyBatis를 설정하고 간단한 예제를 만들어 본 다음, Spring 3로 Bean을 등록하는 예제로 확장시켜 볼 예정이다.

본 예제는 다음과 같은 개발환경하에서 작성되었다.

  • Eclipse Java EE IDE (Juno)
    • PropertiesEditor (by Sou Miyazaki)
  • Java SE 6
  • MyBatis-3.1.1
  • JUnit 4

1. MySQL Table


1
2
3
4
5
6
7
CREATE TABLE user (
    id INT(5) NOT NULL PRIMARY KEY AUTO_INCREMENT,
    username VARCHAR(16) NOT NULL,
    password VARCHAR(16) NOT NULL,
    level INT(2) NOT NULL DEFAULT '0',
    reg_date DATE NOT NULL
);

2. Configuration


development.properties


1
2
3
4
url=jdbc:mysql://localhost/development?characterEncoding=utf-8
driver=com.mysql.jdbc.Driver
user=development
pass=test123



mysql-config.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
<p><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
<configuration>
    <properties resource="exercise/mybatis3/persistence/development.properties"/>
     
    <settings>
        <setting name="defaultExecutorType" value="REUSE"/>
        <setting name="useGeneratedKeys" value="true"/>
    </settings>
     
    <typeAliases>
    <!-- Type Aliases List -->   
    </typeAliases>
     
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="JNDI">
                <property name="initial_context" value="java:comp/env" />
                <property name="data_source" value="jdbc/insure"/>
            </dataSource>
        </environment>
         
        <environment id="testing">
            <transactionManager type="MANAGED">
                <property name="closeConnection" value="false"/>
            </transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}" />
                <property name="url" value="${url}" />
                <property name="username" value="${user}" />
                <property name="password" value="${pass}" />
            </dataSource>
        </environment>
    </environments>
     
    <mappers>
    <!-- Mapper List -->
    </mappers>
</configuration></p>

3. SQL Mapper (CRUD)

UserMapper.xml


1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<mapper namespace="exercise.mybatis3.persistence.UserMapper">
    <insert id="add" parameterType="User"
            useGeneratedKeys="true" keyProperty="id">
        INSERT INTO user (username, password, level, reg_date)
        VALUES (#{username}, #{password}, 1, NOW())
    </insert>
     
    <select id="count" resultType="int">
        SELECT COUNT(*) FROM user
    </select>
</mapper>

UserMapper.java


1
2
3
4
5
6
7
8
9
10
package exercise.mybatis3.persistence;
 
import exercise.mybatis3.domain.User;
 
public interface UserMapper {
     
    public void add(User user);
     
    public int count();
}

4. Domain Object

User.java


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
package exercise.mybatis3.domain;
 
import java.io.Serializable;
 
public class User implements Serializable {
 
    private static final long serialVersionUID = 1L;
     
    private Integer id;
    private String username;
    private String password;
    private Integer level;
    private String regDate;
 
    public User() {
        // TODO Auto-generated constructor stub
    }
     
    public User(String username, String password) {
        this.username = username;
        this.password = password;
    }
 
    public Integer getId() {
        return id;
    }
 
    public void setId(Integer id) {
        this.id = id;
    }
 
    public String getUsername() {
        return username;
    }
 
    public void setUsername(String username) {
        this.username = username;
    }
 
    public String getPassword() {
        return password;
    }
 
    public void setPassword(String password) {
        this.password = password;
    }
 
    public Integer getLevel() {
        return level;
    }
 
    public void setLevel(Integer level) {
        this.level = level;
    }
 
    public String getRegDate() {
        return regDate;
    }
 
    public void setRegDate(String regDate) {
        this.regDate = regDate;
    }
 
}

5. Unit Test (CRUD)

TestUserMapper.java


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
package exercise.mybatis3.test;
 
import static org.junit.Assert.assertThat;
import static org.hamcrest.CoreMatchers.is;
 
import java.io.Reader;
 
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
 
import exercise.mybatis3.domain.User;
import exercise.mybatis3.persistence.UserMapper;
 
public class TestUserMapper {
    static SqlSessionFactory sf;
    User user;
 
    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
        String resource = "exercise/mybatis3/persistence/mybatis-config.xml";
        Reader reader = Resources.getResourceAsReader(resource);
        sf = new SqlSessionFactoryBuilder().build(reader, "testing");
         
    }
     
    @Before
    public void setUp() {
        user = new User("user1", "1234");
    }
 
    @Test
    public void testAdd() {
        SqlSession session = sf.openSession();
         
        try {
            UserMapper mapper = session.getMapper(UserMapper.class);
             
            mapper.add(user);
            assertThat(1, is(mapper.count()));
        } finally {
            session.close();
        }
    }
 
}

출처: http://jeongsam.net/259


'프로그래밍 > ibatis' 카테고리의 다른 글

[MyBatis] $ 과 # 차이점  (0) 2014.11.18
iBatis 복수 parameter넘기는법  (0) 2014.11.18
[스크랩]resultMap, resultClass, parameterClass  (0) 2014.10.14
Posted by 앗뜨거
,
728x90

org.apache.jasper.JasperException: /includee.jspf(1,2) Page directive: illegal to have multiple occurrences of contentType with different values (old: text/html; charset=UTF-8, new: text/html; charset=utf-8)


jsp 모듈화작업시 이런 오류가 나온다면 


나같은경우는 모든페이지를 확인해서  UTF-8 로 되어있는것을 utf-8로 바꾸어줬다.. 대소문자를 구별하다니 못찾을뻔...

Posted by 앗뜨거
,
728x90



체크박스를 보면 위에 "아이디 기억하기와같이 정렬이 되야되는데

부트스트랩3.2 를 예전처럼




1
2
3
4
5
6
7
8
                        <div class="form-group">
                            <div class="col-md-offset-2 col-md-10">
                                <div class="checkbox">
                                    <input type="checkbox" id="chkRememberMe" name="chkRememberMe" />
                                    <label for="chkRememberMe">암호 저장</label>
                                </div>
                            </div>
                        </div>


이런식으로 <div class="checkbox" >  안에 input과 label 을 따로 해주면 밑에 암호저장과 같이 왼쪽으로 밀리고 글씨도 밀린다.


해결방법은




1
2
3
4
5
6
7
8
9
                        <div class="form-group">
                            <div class="col-md-offset-2 col-md-10">
                                <div class="checkbox">
                                    <label>
                                        <input type="checkbox" id="chkRememberMe" name="chkRememberMe" />아이디 기억하기
                                    </label>
                                </div>
                            </div>
                        </div>



이런식으로 체크박스로 묶어준다음에 

라벨로 인풋을 묶어주면 해결된다. 

'프로그래밍 > BootStrap' 카테고리의 다른 글

부트스트랩 2.x to 3.2  (0) 2014.10.05
Posted by 앗뜨거
,
728x90

building workspace has encountered a problem errors occurred during the build 오류와함께


Failure to transfer org.apache.maven.plugins:maven-resources-plugin:pom:2.6 의 maven 오류


Description Resource Path Location Type Could not calculate build plan: Failure to transfer org.apache.maven.plugins:maven-compiler-plugin:pom:2.0.2 from http://repo1.maven.org/maven2was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced. Original error: Could not transfer artifact org.apache.maven.plugins:maven-compiler-plugin:pom:2.0.2 from/to central (http://repo1.maven.org/maven2): No response received after 60000 ExampleProject Unknown Maven Problem



이런 도움말이떴을떄 

 


나는 http://stackoverflow.com/questions/5074063/maven-error-failure-to-transfer 를 참조해서


cmd 에서


find ~/.m2  -name "*.lastUpdated" -exec grep -q "Could not transfer" {} \; -print -exec rm {} \;


을 치고


cd %userprofile%\.m2\repository for /r %i in (*.lastUpdated) do del %i


를 한다음


프로젝트를 Then rightclick on your project in eclipse and choose Maven->Update Dependencies

Posted by 앗뜨거
,
728x90

1. http://startbootstrap.com/


2. http://bootswatch.com/

Posted by 앗뜨거
,
728x90

iBatis 는 실제적으로 많이 사용 하고 있거나, 그렇지 않으면 앞으로 사용 할 때

굉장히 헷갈리는 부분이 있다.


바로 어떻게 value object와 column name을 맵핑 시킬 것인가,

혹은 값들을 어떻게 jsp에 뿌릴 것 인가, 즉슨 자바 코드에 어떻게 담아서 운반 할 것인가

에 대해 많은 고민이 있다.


이제 때에 맞는 iBatis value 맵핑에 대해 알아보자.


우선, 게시판을 예로 들겠다.

1. 글 작성 후 글을 DB에 insert 시킬 시

여기선 아마 write.jsp 라는 페이지에서 form값을 vo에 담아 controller 에다 넘겨 줄 것이다.


// vo 객체를 인스턴스화 하여 가져온다

<typeAlias alias="boardVo" type="jh.board.vo.BoardVO"/>


<insert id="write" parameterClass="boardVo">


이렇게 parameterClass는 vo값을 insert만 하고 아무런 result값도 가져오지 않을 때 주로 쓰인다.


2. 글 목록들을 Select 할 때

여기선 객체 하나만 가져오는게 아니라, 객체의 리스트 제네릭을 리턴 받는다.


<resultMap id="BoardResult" class="boardVo">

<result property="num" column="num" columnIndex="1" />

<result property="author" column="author" columnIndex="2" />

<result property="title" column="title" columnIndex="3" />

<result property="content" column="content" columnIndex="4" />

<result property="writeday" column="writeday" columnIndex="5" />

<result property="readcnt" column="readcnt" columnIndex="6" />

</resultMap>


<select id="list" resultMap="BoardResult" parameterClass="boardVo">


resultMap을 이용하여 boardVo 객체의 겟/셋 변수명과 DB의 column 명을 맵핑 한 후

그 결과를 조회하여 resultMap 을 Controller단 까지 넘겨 받는다.


여기서 유심히 볼 것은 그저 select만 한다면 paramterClass가 필요 없다.

하지만 검색 시 검색명과 검색값을 select 문에 넣기 위해 paramterClass가 또 쓰여 졌다.


3. 상세글이나 업데이트 시


<select id="retrieve" resultMap="BoardResult">


<select id="updateForm" resultMap="BoardResult">


위와 마찬가지로 resultMap을 사용 하여 값을 return 받아 프레젠테이션 층에 넘겨 준다.


4. 그런데 resultClass 는 어디서 사용 될까 ?


<select id="count" resultClass="Integer">

SELECT 

COUNT( num )

FROM board

</select>


위와 같이 그냥 Integer(정수형) 으로 num의 count만 받고 싶다면 저렇게 쓰면 된다.


물론 Delete문과 같이 리턴 받을게 없고 그저 삭제만 시킨다 함은 resultMap, resultClass를 쓸 필요가 없는 것이다.


요약 하자면,

resultMap Object를 return 받을 때 사용

resultClass Integer 등 1개의 value형을 return 받을 때 사용

parameterClass Object를 ibatis DML(#num#, #title#)문에 적용 시키고 싶을 때 사용




출처: http://denodo1.tistory.com/entry/resultMap-resultClass-parameterClass-%EC%97%90-%EA%B4%80%ED%95%9C-%EA%B3%A0%EC%B0%B0

'프로그래밍 > ibatis' 카테고리의 다른 글

[MyBatis] $ 과 # 차이점  (0) 2014.11.18
iBatis 복수 parameter넘기는법  (0) 2014.11.18
Mybatis 기본 사용법  (0) 2014.10.28
Posted by 앗뜨거
,
728x90
Error: The type org.springframework.dao.DataAccessException cannot be resolved. It is indirectly referenced from required .class files

해결법: RowMapper 선언할 때 spring-jdbc.jar파일만 import할 경우 하위 method인 mapRow 선언시 에러 발생 . spring-tx.jar가 추가로 필요함

메이븐에 추가
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.1.1.RELEASE</version>
</dependency>


Posted by 앗뜨거
,
728x90

1. 오라클


<%
String DB_URL = "jdbc:oracle:thin:@localhost:1521:ORCL";


String DB_USER    = "scott"; // DB USER명
String DB_PASSWORD = "tiger"; // 패스워드

Connection con = null;
Statement  stmt   = null;
ResultSet rs = null;
String sql=null;

try
 {
    Class.forName("oracle.jdbc.driver.OracleDriver");
    con = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);    
  }catch(SQLException e){out.println(e);}
%>



2. mysql


<%


Connection conn = null;                                        // null로 초기화 한다.


try{

String url = "jdbc:mysql://localhost:3306/jdbcTest";        // 사용하려는 데이터베이스명을 포함한 URL 기술

String id = "testid";                                                    // 사용자 계정

String pw = "testpw";                                                // 사용자 계정의 패스워드


Class.forName("com.mysql.jdbc.Driver");                       // 데이터베이스와 연동하기 위해 DriverManager에 등록한다.

conn=DriverManager.getConnection(url,id,pw);              // DriverManager 객체로부터 Connection 객체를 얻어온다.

out.println("제대로 연결되었습니다.");                            // 커넥션이 제대로 연결되면 수행된다.


}catch(Exception e){                                                    // 예외가 발생하면 예외 상황을 처리한다.

e.printStackTrace();

}

%>

Posted by 앗뜨거
,
728x90

1. 위키 독스 온라인 책 제작 공유 플랫폼 https://wikidocs.net/



2. 웹개발 강의 정리 http://wiki.gurubee.net/display/LECTURE/Home




Posted by 앗뜨거
,
728x90

bootstrap 3.2.zip

bootstrap 2.2.zip

Migrating from 2.x to 3.2

Bootstrap 3 is not backwards compatible with v2.x. Use this section as a general guide to upgrading from v2.x to v3.0. For a broader overview, see what's new in the v3.0 release announcement.

Major class changes

This table shows the style changes between v2.x and v3.0.

Bootstrap 2.xBootstrap 3.0
.row-fluid.row
.span*.col-md-*
.offset*.col-md-offset-*
.brand.navbar-brand
.navbar .nav.navbar-nav
.nav-collapse.navbar-collapse
.nav-toggle.navbar-toggle
.btn-navbar.navbar-btn
.hero-unit.jumbotron
.icon-*.glyphicon .glyphicon-*
.btn.btn .btn-default
.btn-mini.btn-xs
.btn-small.btn-sm
.btn-large.btn-lg
.alert-error.alert-danger
.visible-phone.visible-xs
.visible-tablet.visible-sm
.visible-desktopSplit into .visible-md .visible-lg
.hidden-phone.hidden-xs
.hidden-tablet.hidden-sm
.hidden-desktopSplit into .hidden-md .hidden-lg
.input-block-level.form-control
.control-group.form-group
.control-group.warning .control-group.error .control-group.success.form-group.has-*
.checkbox.inline .radio.inline.checkbox-inline .radio-inline
.input-prepend .input-append.input-group
.add-on.input-group-addon
.img-polaroid.img-thumbnail
ul.unstyled.list-unstyled
ul.inline.list-inline
.muted.text-muted
.label.label .label-default
.label-important.label-danger
.text-error.text-danger
.table .error.table .danger
.bar.progress-bar
.bar-*.progress-bar-*
.accordion.panel-group
.accordion-group.panel .panel-default
.accordion-heading.panel-heading
.accordion-body.panel-collapse
.accordion-inner.panel-body

What's new

We've added new elements and changed some existing ones. Here are the new or updated styles.

ElementDescription
Panels.panel .panel-default .panel-body .panel-title .panel-heading .panel-footer.panel-collapse
List groups.list-group .list-group-item .list-group-item-text .list-group-item-heading
Glyphicons.glyphicon
Jumbotron.jumbotron
Extra small grid (<768px).col-xs-*
Small grid (≥768px).col-sm-*
Medium grid (≥992px).col-md-*
Large grid (≥1200px).col-lg-*
Responsive utility classes (≥1200px).visible-lg .hidden-lg
Offsets.col-sm-offset-* .col-md-offset-* .col-lg-offset-*
Push.col-sm-push-* .col-md-push-* .col-lg-push-*
Pull.col-sm-pull-* .col-md-pull-* .col-lg-pull-*
Input height sizes.input-sm .input-lg
Input groups.input-group .input-group-addon .input-group-btn
Form controls.form-control .form-group
Button group sizes.btn-group-xs .btn-group-sm .btn-group-lg
Navbar text.navbar-text
Navbar header.navbar-header
Justified tabs / pills.nav-justified
Responsive images.img-responsive
Contextual table rows.success .danger .warning .active .info
Contextual panels.panel-success .panel-danger .panel-warning .panel-info
Modal.modal-dialog .modal-content
Thumbnail image.img-thumbnail
Well sizes.well-sm .well-lg
Alert links.alert-link

What's removed

The following elements have been dropped or changed in v3.0.

ElementRemoved from 2.x3.0 Equivalent
Form actions.form-actionsN/A
Search form.form-searchN/A
Form group with info.control-group.infoN/A
Fixed-width input sizes.input-mini .input-small .input-medium .input-large.input-xlarge .input-xxlargeUse .form-control and the grid systeminstead.
Block level form input.input-block-levelNo direct equivalent, but forms controls are similar.
Inverse buttons.btn-inverseN/A
Fluid row.row-fluid.row (no more fixed grid)
Controls wrapper.controlsN/A
Controls row.controls-row.row or .form-group
Navbar inner.navbar-innerN/A
Navbar vertical dividers.navbar .divider-verticalN/A
Dropdown submenu.dropdown-submenuN/A
Tab alignments.tabs-left .tabs-right .tabs-belowN/A
Pill-based tabbable area.pill-content.tab-content
Pill-based tabbable area pane.pill-pane.tab-pane
Nav lists.nav-list .nav-headerNo direct equivalent, but list groups and.panel-groups are similar.
Inline help for form controls.help-inlineNo exact equivalent, but .help-block is similar.
Non-bar-level progress colors.progress-info .progress-success .progress-warning.progress-dangerUse .progress-bar-* on the .progress-bar instead.


Posted by 앗뜨거
,