Mybatis 한글깨짐


jdbc.url=jdbc:mysql://localhost:3306/디비명?useUnicode=true&characterEncoding=utf8


Mybatis에서 parametertype이 String이나 int 같은 기본형인 경우

=============================
<if test="abc == null ">
    ...
</if>
=============================
위와 같이 사용시

There is no getter for property named 'abc' in 'class java.lang.String'
라는 에러 발생

...
이럴때는

=============================
<if test="_parameter == null ">
    ...
</if>
=============================
위와 같이 테스트할 파라미터 이름을 '_parameter' 로 바꿔주면
정상적으로 동작한다.


참고 :
http://devwa.com/47






http://hangaebal.blogspot.kr/2014/12/mybatis-parametertype-string-test-there.html

1. STS로 Spring MVC Project 생성 후 접속 확인

- 한글이 깨져서 나오니 home.jsp 파일에
<%@ page language="java" contentType="text/html; charset=UTF-8"  %> 추가


2. pom.xml에 dependency 추가

(버전 확인 - http://mvnrepository.com/)
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.2.7</version>
</dependency>

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>1.2.2</version>
</dependency>

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.31</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>3.2.3.RELEASE</version>
</dependency>



3. root-context.xml에 bean 추가

<bean id="dataSource" class="org.apache.ibatis.datasource.pooled.PooledDataSource">
    <property name="driver" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost:3306/스키마이름"/>
    <property name="username" value="계정"/>
    <property name="password" value="암호"/>
</bean>

<bean id ="sqlSessionFactory" class= "org.mybatis.spring.SqlSessionFactoryBean" >
    <property name ="dataSource" ref= "dataSource"></property >
    <property name ="configLocation"
        value= "classpath:/mybatis/mybatis-config.xml" >
    </property >
</bean >

<bean id ="transactionManager"
    class= "org.springframework.jdbc.datasource.DataSourceTransactionManager" >
    <property name ="dataSource" ref= "dataSource"></property >
</bean >

<bean id ="sqlSession"
    class= "org.mybatis.spring.SqlSessionTemplate" >
    <constructor-arg ref= "sqlSessionFactory"></constructor-arg >

</bean >



4. mybatis-config.xml 생성

(src/main/resources/mybatis/mybatis-config.xml)

<?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>
    <mappers >
        <mapper resource ="/mybatis/mapper-sample.xml"/>
    </mappers >
</configuration>



5. mapper-sample.xml 생성

(src/main/resources/mybatis/mapper-sample.xml)
<?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= "userControlMapper" >
    <select id ="selectSample" parameterType="java.util.HashMap" resultType= "java.util.HashMap">
        SELECT *
        FROM TEST_USERS
        WHERE NAME = #{name}
    </select>

    <insert id ="insertTable01" parameterType="java.util.HashMap" >
        INSERT INTO TEST_USERS
        (NAME, EMAIL)
        VALUES
        ( #{name}, #{email} )
    </insert>

</mapper>



6. MySQL에 테스트 table과 data 준비

CREATE TABLE `스키마이름`.`TEST_USERS` (
    `NO` INT NOT NULL AUTO_INCREMENT,
    `NAME` VARCHAR(100) NULL,
    `EMAIL` VARCHAR(100) NULL,
    PRIMARY KEY (`NO`),
    UNIQUE INDEX `NO_UNIQUE` (`NO` ASC));

INSERT INTO TEST_USERS (NAME, EMAIL) VALUES ("han", "han@test.com");



7. HomeController.java 수정

@Controller
public class HomeController {

@Controller
public class HomeController {
    
    // <--- 추가 
    @Autowired
    private SqlSession sqlSession;
    // 추가 --->
    
    private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
    
    /**
    * Simply selects the home view to render by returning its name.
    */
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String home(Locale locale, Model model) {
        logger.info("Welcome home! The client locale is {}.", locale);
        
        Date date = new Date();
        DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
        
        String formattedDate = dateFormat.format(date);
        
        model.addAttribute("serverTime", formattedDate );
        
        // <--- 추가 
        HashMap<String, String> input = new HashMap<String, String>();
        input.put("name", "han");
        List<HashMap<String, String>> outputs = sqlSession.selectList("userControlMapper.selectSample", input);
        System.out.println(outputs.toString());
        // 추가 --->
        
        return "home";
}
    
}



8. 브라우저로 server 접속 후 Console 출력 확인

- [{NO=1, EMAIL=han@test.com, NAME=han}]


참고 :
http://blog.naver.com/refreshin/150170189512








http://hangaebal.blogspot.kr/2014/08/spring-spring-tool-suitests-mysql.html


*라이브러리 파일 준비
- https://github.com/mybatis > mybatis-3 > download
라이브러리 다운로드 후 WEB-INF/lib로  복사


*핵심 컴포넌트
1. SqlSessionFactoryBuilder
- mybatis 설정 파일의 내용으로 SqlSessionFactory 생성
2. SqlSessionFactory
- SqlSession 객체를 생성
3. SqlSession
- 실제 SQL 실행하는 객체, JDBC 드라이버 사용
4. SQL 맵퍼 파일
- SQL 문을 담고 있는 파일. SqlSession 객체가 참조함


*SqlSession 주요 메서드
1. selectList()
- SELECT 실행. 객체(Object) 목록을 반환

2. selectOne()
- SELECT 실행. 객체 하나를 반환

3. insert()
- INSERT 실행. 추가된 갯수(int) 반환

4. update()
- UPDATE 실행. 변경된 갯수 반환

5. delete()
- DELETE 실행. 삭제된 갯수 반환


*사용
- DAO : List<E> selectList(String sqlId, 매개변수)
  (sqlId ==> 맵퍼이름 + sql아이디)

- mapper :
<mapper namespace="맵퍼이름">
<select id="sql아이디" parameterType="객체명">
SQL문
VALUES (#{프로퍼티명},  #{프로퍼티명}, ...)
- #{프로퍼티}명 - 은 객체의 getter/setter를 사용
- 매개변수가 int 등 기본 데이터 형인 경우 프로퍼티 명은 아무 이름이나 써도 상관없다.




http://hangaebal.blogspot.kr/2014/06/mybatis.html

+ Recent posts