在上一篇文章中写了配置xml文件,那么在这一篇文章中就写一下mapper映射的心得体会。
MyBatis 的真正强大在于它的映射语句,也是它的魔力所在。由于它的异常强大,映射器的 XML 文件就显得相对简单。如果拿它跟具有相同功能的 JDBC 代码进行对比,你会立即发现省掉了将近 95% 的代码。MyBatis 就是针对 SQL 构建的,并且比普通的方法做的更好。
1.mybatis映射
映射 都需要使用接口来实现相关操作。它们之间的联系如下:
作用:映射器由 映射文件XML(或注解)以及对应的接口组成
1,定义参数类型
2,缓存描述
3,描述SQL语句
4, 定义查询结果 以及查询结果和JavaBean的映射关系
Login.java
public class Login{
private int id;
private String count;
private String password;
public int getId() {return id;}
public void setId(int id) {this.id = id;}
public String getCount() {return count;}
public void setCount(String count) {this.count = count;}
public String getPassword() {return password;}
public void setPassword(String password) {
this.password = password;
}
public Login(String count, String password) {
this.count = count;
this.password = password;
}
public Login() {}
}
LoginMapper.java
import java.util.List;
import com.testmybatis.bean.Login;
public interface LoginMapper {
public List<Login> loginQuery();//查询全部登陆信息
}
login-mapper.xml
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- 名称空间 就是 接口 的包路径 -->
<mapper namespace="com.testmybatis.mapper.LoginMapper">
//将缓存设置成LRU :最近最久未使用
<cache eviction="LRU" />
//id是接口对应的方法名 resultType:返回参数类型为Login
<select id ="loginQuery" resultType="Login">
select * from login
</select>
</mapper>
2.SqlSessionFactory 和 SqlSession 的了解
1).每个基于 MyBatis 的应用都是以一个 SqlSessionFactory 的实例为中心的。SqlSessionFactory 的实例可以通过 SqlSessionFactoryBuilder 获得。而 SqlSessionFactoryBuilder 则可以从 XML 配置文件或一个预先定制的 Configuration 的实例构建出 SqlSessionFactory 的实例。
2).从 XML 文件中构建 SqlSessionFactory 的实例非常简单,建议使用类路径下的资源文件进行配置。但是也可以使用任意的输入流(InputStream)实例,包括字符串形式的文件路径或者 file:// 的 URL 形式的文件路径来配置。MyBatis 包含一个名叫 Resources 的工具类,它包含一些实用方法,可使从 classpath 或其他位置加载资源文件更加容易
3.测试是否成功
TestMybatisSelect .java
public class TestMybatisSelect {
public void LoginSelect() {
SqlSession session = null;
SqlSessionFactory sqlSessionFactory =null;
String resource = "mybatis-config.xml";
InputStream inputStream =null;;
try {
inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
session=sqlSessionFactory.openSession();
//映射接口
LoginMapper mapper = session.getMapper(LoginMapper.class);
List<Login> log = mapper.loginQuery();
//使用Gson 打印结果
Gson g= new Gson();
System.out.println(g.toJson(log));
} catch (Exception e) {
e.printStackTrace();
}finally {
if(session != null) session.close();
}
}
public static void main(String[] args) {
TestMybatisSelect tms = new TestMybatisSelect();
tms.LoginSelect();
}
}
具体的mybatis的简单配置可以参考我的上一篇文章。
如果想深入的了解,可以去官网看一看相关文档