我们在使用mybatis操作数据库时,需要两个jar包,分别是ojdbc.jar和mybatis.jar分别用以链接数据库和操作数据库使用。
然后呢,就该配置核心配置文件了。
<?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="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl" />
<property name="username" value="scott" />
<property name="password" value="tiger" />
</dataSource>
</environment>
</environments>
</configuration>
然后我们可以写一个测试类来测试是否能链接成功,
<pre name="code" class="java">public class MybatisJdbc {
public static void main(String[] args) {
try {
Reader rd=Resources.getResourceAsReader("config.xml");
SqlSessionFactory sf=new SqlSessionFactoryBuilder().build(rd);
SqlSession session=sf.openSession();
System.out.println(session);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
如果能在控制台输出Session,就表示我们已经成功链接了数据库,下一步就可以操作数据库了:
先写一个实体类Dept用来对应scott用户下的Dept表,然后在为这个类写映射文件*.xml
<pre name="code" class="html"><?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="dao.EmpDao">
<delete id="delete" parameterType="int">
delete from dept where deptno=#{id}
</delete>
<select id="select" resultType="entity.Dept" parameterType="int">
select * from dept where deptno=#{id}
</select>
</mapper>
在这个xml文件中我们可以写要对数据库进行的操作,他们都有一个唯一的id,不要忘了在核心配置文件中进行关联映射。
下一步
<pre name="code" class="java">public static void main(String[] args) {
try {
Reader rd=Resources.getResourceAsReader("config.xml");
SqlSessionFactory sf=new SqlSessionFactoryBuilder().build(rd);
SqlSession session=sf.openSession();
Dept dept=session.selectOne("select", 20);
System.out.println(dept);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
从控制台输出Dept对象,说明我们已经查询成功了。
在Dao模式下操作数据库
DeptDao deptDao =session.getMapper(DeptDao.class);
deptDao.findbyid(56);