简介:
iBatis更名为MyBatis,作出了些修改. 如以前使用SqlMapClient进行数据库操作,现在使用SqlSession.
jar包
普通的javaBean: domain.User
与bean对应的SQL映射文件: maps/User.xml
MyBatis需要的配置文件: mybatis.cfg.xml
1. 需要的jar包: mybatis-3.0.2.jar (只有此一个是必须的,比iBatis清楚多了).
2. 类User:
package domain;
public class User {
private int id;
private String name;
public User() {}
public User(String name) { this(0, name); }
public User(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
@Override
public String toString() { return "ID: " + id + ", Name: " + name; }
}
3. User.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="User">
<select id="selectUser" parameterType="int" resultType="User"><![CDATA[
select * from user where id = #{id}
]]></select>
</mapper>
4. MyBatis需要的配置文件:
<?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>
<typeAlias alias="User" type="domain.User" />
</typeAliases>
<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/test?useUnicode=true&characterEncoding=UTF-8" />
<property name="username" value="root" />
<property name="password" value="" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="maps/User.xml" />
</mappers>
</configuration>
5. 使用MyBatis访问数据库:
import java.io.IOException;
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 domain.User;
public class Test {
public static void main(String[] args) throws IOException {
String resource = "mybatis.cfg.xml";
Reader reader = Resources.getResourceAsReader(resource);
SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = ssf.openSession();
try {
User user = (User) session.selectOne("selectUser", "3");
System.out.println(user);
} catch (Exception e) {
e.printStackTrace();
} finally {
session.close();
}
}
}