mybatis的oracle数据库操作

我们在使用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);


 

                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值