Whats Mybatis
持久层框架, 替代MVC层中DAO,因为DAO 层的需求就是 :能与数据库交互的对象、 能执行SQL语句。
不同于JDBC的connection,MyBatis 中有个SqlSession ,什么是SqlSession,以及它的作用是什么:
◆
1 向SQL语句传入参数
2执行SQL语句
3 获取执行SQL语句的结果
4 事务的控制
如何获得SqlSession
1 通过配置文件获取数据库连接的相关需求
2 通过配置文件构建SqlSessionFactory
3 通过SqlSessionFactory 打开openSession
下面看代码具体操作:
目录结构:
MyBatis 配置文件
MySQL-connector…….对应的驱动文件
Ojdbc14.jar……..oracle 对应的驱动文件
Userinfo.java(数据库对应的实体类)
package bean; public class Userinfo { private String uname;
private String upass;
private int id; public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getUpass() {
return upass;
}
public void setUpass(String upass) {
this.upass = upass;
} }
Mapper
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="UserinfoMapper">
<!--
public String getuser (int id){}
-->
<select id="getuser" parameterType="int" resultType="java.lang.String" >
select uname from userinfo where id=#{id}
</select>
</mapper>
Test
package Test; import java.io.InputStream; import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class Demo { /**
*
* 测试连接数据库,执行SQL语句
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub // 加载Mybatis的主配置文件
InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml"); // 创建生产session的工厂类 session不是作用域 -- 相当于connection
SqlSessionFactoryBuilder sfb = new SqlSessionFactoryBuilder();
SqlSessionFactory ssf = sfb.build(is);
// 打开session
SqlSession session=ssf.openSession();
//执行sql语句
/**
* UserinfoMapper 是UserinfoMapper.xml namespace 的名字
* getuser select id 对应的方法名字
* 3 是传的参数
*/ String name=session.selectOne("UserinfoMapper.getuser", 3);
System.out.println("name:"+ name);
session.close();
System.out.println("over"); } }
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" />
<!-- 配置数据源 相当于JDBC连接数据库
Class.forName("oracle.jdbc.driver.OracleDriver");
String user = "scott";
String password = "tiger";
String url = "jdbc:oracle:thin:@localhost:1521:orcl";
-->
<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>
<!-- 读取Mapper包下的UserinfoMapper.xml文件 -->
<mappers>
<mapper resource="Mapper/UserinfoMapper.xml" />
</mappers>
</configuration>
控制台输出的文件