作为新手还是先照着做个小例子
一.导入ibatis包和mysql的jdbc包。
二.新建一个User类,包含id,name,sex。
三.写ibatis配置文件,SqlMapConfig.xml。
四.写sql映射的xml文件User.xml。
五.初始化配置文件并查询。
User.java
package com.forrest.ibatis.test.domain;
import java.io.Serializable;
public class User implements Serializable
{
private Integer id;
private String name;
private Integer sex;
public Integer getId()
{
return id;
}
public void setId(Integer id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public Integer getSex()
{
return sex;
}
public void setSex(Integer sex)
{
this.sex = sex;
}
}
SqlMapConfig.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> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/ibatis1"/> <property name="username" value="java"/> <property name="password" value="java"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/forrest/ibatis/test/User.xml"/> </mappers> </configuration>
User.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"
"http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">
<mapper namespace="UserMapper">
<select id="selectOne" parameterType="java.lang.Integer" resultType="com.forrest.ibatis.test.domain.User">
select * from t_user where id = #{id}
</select>
</mapper>
main方法
public static void main(String[] args) throws IOException
{
String resource = "com/forrest/ibatis/test/SqlMapConfig.xml";
Reader reader;
reader = Resources.getResourceAsReader(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession sqlSession = sqlSessionFactory.openSession();
User user = (User)sqlSession.selectOne("UserMapper.selectOne", "1");
System.out.println(user.getId());
System.out.println(user.getName());
System.out.println(user.getSex());
}