iBATIS 입문
4456 단어 ibati
1: jar 가방 가입
2: 데이터 원본 만 들 기 (configuration. 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>
<typeAliases>
<!-- user -->
<typeAlias type="com.forum.po.User" alias="User" />
</typeAliases>
<!-- BD2 -->
<environments default="development">
<environment id="development">
<transactionManager type="jdbc" />
<dataSource type="POOLED">
<property name="driver" value="com.ibm.db2.jcc.DB2Driver" />
<property name="url" value="jdbc:db2://localhost:50000/forum" />
<property name="username" value="DB2ADMIN" />
<property name="password" value="admin" />
</dataSource>
</environment>
</environments>
<mappers>
<!--userMapper.xml “dao” -->
<mapper resource="myBatis/userMapper.xml" />
</mappers>
</configuration>
3: 실체 클래스 만 들 기 USER
package com.forum.po;
/**
*
*
* @author db2admin
*
*/
public class User extends Entity {
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public User() {
}
}
4: dao 인 터 페 이 스 를 만 듭 니 다. Mapper 인터페이스 라 고 할 수 있 습 니 다. UserMapper
package com.forum.dao;
import com.forum.po.User;
public interface UserMapper {
public User findById(String Id);
}
5: dao 를 만 드 는 것 은 hibenarte 와 달리 xml 파일, 즉 userMapper. 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">
<!-- dao namespace -->
<mapper namespace="com.forum.dao.UserMapper">
<!-- findById User -->
<select id="findById" parameterType="HashMap" resultType="User">
select
* from butone.student where id=#{id}
</select>
</mapper>
6: 테스트 클래스, MyBatisTest
package com.forum.test;
import java.io.IOException;
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 com.forum.dao.UserMapper;
import com.forum.po.User;
/**
* myBatis
*
* @author db2admin
*
*/
public class MyBatisTest {
/**
* MyBatis SqlSessionFactory
* SqlSessionFactory SqlSession, , SqlSession ,commit,rollback,close 。
* @return
*/
private static SqlSessionFactory getSessionFactory() {
SqlSessionFactory sessionFactory = null;
String resource = "configuration.xml";
try {
sessionFactory = new SqlSessionFactoryBuilder().build(Resources
.getResourceAsReader(resource));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return sessionFactory;
}
public static void main(String[] args) {
SqlSession sqlSession = getSessionFactory().openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.findById("1");
System.out.println(user.getName());
}
}