一、为项目添加mybatis-3.1.1.jar文件和对应数据库的驱动Jar文件。
二、创建配置文件mybatis.xml
<?xml version="1.0"encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<typeAliastype="com.kero99.wp.entity.Message"alias="Message"/>
</typeAliases>
<environmentsdefault="Oracle">
<environmentid="Oracle">
<transactionManager type="JDBC"/>
<dataSourcetype="POOLED">
<property name="driver"value="oracle.jdbc.driver.OracleDriver"/>
<property name="url"value="jdbc:oracle:thin:@127.0.0.1:1521:tcaccp"/>
<property name="username" value="sys assysdba" />
<property name="password"value="tcaccp" />
</dataSource>
</environment>
</environments>
<mappers>
<mapperresource="com/kero99/wp/entity/MessageMapper.xml"/>
</mappers>
</configuration>
此文件主要用来设置数据库的链接必须的参数,以及关联映射Mapper文件。
三、创建数据库与数据表的映射类
package com.kero99.wp.entity;
import java.util.Date;
public class Message {
private int id;
private String title;
private String content;
private Date bdate;
publicint getId() {
return id;
}
publicvoid setId(int id) {
this.id = id;
}
publicString getTitle() {
return title;
}
publicvoid setTitle(String title) {
this.title = title;
}
publicString getContent() {
return content;
}
publicvoid setContent(String content) {
this.content = content;
}
publicDate getBdate() {
return bdate;
}
publicvoid setBdate(Date bdate) {
this.bdate = bdate;
}
}
四、创建的Mapper接口,定义方法
package com.kero99.wp.mapper;
import java.util.List;
import com.kero99.wp.entity.Message;
public interface MessageMapper {
public List<Message>selectAll();
}
五、创建映射配置文件MessageMapper.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">
<mappernamespace="com.kero99.wp.mapper.MessageMapper">
<select id="selectAll"resultType="Message">
select * from Message
</select>
</mapper>
将数据库操作接口Mapper中的方法与SQL语句绑定
六、测试
SqlSessionFactory factory=newSqlSessionFactoryBuilder().build(Test.class.getClassLoader().getResourceAsStream("mybatis.xml"));
SqlSession session=factory.openSession();
MessageMappermapper=session.getMapper(MessageMapper.class);
List<Message>list=mapper.selectAll();
for (Message message : list) {
System.out.println(message.getTitle());
}
加载配置文件mybatis.xml,获取Session并创建Mapper对象。
调用方法测试.