MyBatis是一个支持普通SQL查询,存储过程和高级映射的优秀持久层框架。MyBatis消除了几乎所有的JDBC代码和参数的手工设置以及对结果集的检索封装。MyBatis可以使用简单的XML或注解用于配置和原始映射,将接口和Java的POJO(Plain Old Java Objects,普通的Java对象)映射成数据库中的记录。
一对一映射
在生活中,一对一的例子还是有的,比如啦,学生和身份证哦,或者在我国,实行的是一夫一妻制度哦。那么我们以学生和身份证每个学生只有一张身份证,而每张身份证的主人当然只有一个啦。
数据库脚本:
-- 删除数据库 drop database if exists mybaits; -- 创建数据库 create database if not exists mybatis default character set utf8; -- 选择数据库 use mybatis; -- 删除数据表 drop table if exists student ; drop table if exists card; -- 创建数据表 create table card( cid int(255), num varchar(18), constraint pk_cid primary key (cid) ); create table student( sid int(255), sname varchar(32), scid int(255), constraint pk_sid primary key (sid), constraint fk_scid foreign key (scid) references card(cid) ); -- 增加测试数据 insert into card (cid,num) values(1,'123456789012345678'); insert into student (sid,sname,scid) values(1,'哈哈',1);
新建一个one2one.Card.java类
package one2one;
import java.io.Serializable;
@SuppressWarnings("serial")
public class Card implements Serializable{
private Integer cid;
private String num;
public Integer getCid() {
return cid;
}
public void setCid(Integer cid) {
this.cid = cid;
}
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num;
}
}
新建one2one.Student.java类
package one2one;
import java.io.Serializable;
@SuppressWarnings("serial")
public class Student implements Serializable{
private Integer sid;
private String sname;
private Card card;
public Integer getSid() {
return sid;
}
public void setSid(Integer sid) {
this.sid = sid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public Card getCard() {
return card;
}
public void setCard(Card card) {
this.card = card;
}
}
在one2one包下新建CardMapper.xml文件
同理,在one2one包下新建StudentMapper.xml文件
在src下新建一个mybatis.cfg.xml文件,并包含StudentMapper.xml和CardMapper.xml文件
在util包下新建一个工具类MyBatisUtil.java类
package util;
import java.io.IOException;
import java.io.Reader;
import java.sql.Connection;
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 MyBatisUtil {
private static ThreadLocal threadLocal = new ThreadLocal();
public static SqlSessionFactory sqlSessionFactory ;
//私有化构造方法
private MyBatisUtil(){}
//加载位于src/Mybatis.cfg.xml
static{
try {
Reader reader = Resources.getResourceAsReader("mybatis.cfg.xml");
sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSqlSession(){
//从当前线程中获取SqlSession对象
SqlSession sqlSession = threadLocal.get();
if(sqlSession == null){
if(sqlSessionFactory != null){
sqlSession = sqlSessionFactory.openSession();
//讲sqlSession与当前线程绑定在一起
threadLocal.set(sqlSession);
}
}
return sqlSession;
}
public static void closeSqlSession(){
//从当前线程中获取SqlSession对象
SqlSession sqlSession = threadLocal.get();
//如果SqlSession对象非空
if(sqlSession != null){
//关闭SqlSession对象
sqlSession.close();
//分离当前线程与SqlSession的关系
threadLocal.remove();
}
}
//测试
public static void main(String[] args) {
SqlSession sqlSession = MyBatisUtil.getSqlSession();
Connection conn= sqlSession.getConnection();
System.out.println(conn != null ?"连接成功":"连接失败");
}
}
新建持久层类StuentCardDAO.java类
package one2one;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import util.MyBatisUtil;
public class StudentCardDAO {
public Student findById(Integer id) throws Exception{
SqlSession sqlSession = null;
try {
sqlSession = MyBatisUtil.getSqlSession();
return sqlSession.selectOne("studentNameSpace.findById", id);
} catch (Exception e) {
e.printStackTrace();
throw e;
}finally{
MyBatisUtil.closeSqlSession();
}
}
//测试 查询1号学生的信息与身份证信息
@Test
public void testFindById() throws Exception{
StudentCardDAO dao = new StudentCardDAO();
Student student = dao.findById(1);
System.out.println(student.getSid()+":"+student.getSname() }
}
这时我们只能查询1号学生的姓名,但是我们不能去查询它的身份号号,因为此时的card属性的值为null,从StudentMapper.xml中可以看出
MyBatis在解析这一句的时候只能将查询的数据封装到sid,sname中,所以怎么办?
在StudentMapper.xml中的
增加
那么此时的StudentMapper.xml的完整内容如下:
现在可以测试学生的身份证号码了
将持久层类StuentCardDAO.java类的测试方法改为
//测试 查询1号学生的信息与身份证信息
@Test
public void testFindById() throws Exception{
StudentCardDAO dao = new StudentCardDAO();
Student student = dao.findById(1);
System.out.println(student.getSid()+":"+student.getSname()+":"+student.getCard().getNum());
}
同理
在StudentDAO.java类中增加 查询“哈哈”学生的信息与身份证信息的方法
public Student findByName(String name) throws Exception{
SqlSession sqlSession = null;
try {
sqlSession = MyBatisUtil.getSqlSession();
return sqlSession.selectOne("studentNameSpace.findByName", name);
} catch (Exception e) {
e.printStackTrace();
throw e;
}finally{
MyBatisUtil.closeSqlSession();
}
}
并增加测试方法哦
//测试 查询“哈哈”学生的信息与身份证信息
@Test
public void testFindByName() throws Exception{
StudentCardDAO dao = new StudentCardDAO();
Student student = dao.findByName("哈哈");
System.out.println(student.getSid()+":"+student.getSname()+":"+student.getCard().getNum());
}
当然如果你现在就测试,你会死的很惨,因为你没有在StudentMapper.xml文件中配置
select s.sid,s.sname,c.cid,c.num from student s,card c where s.scid = c.cid and s.sname = #{sname}
这样就可以测试成功了。大功告成。
完整代码如下:
MySQL数据库脚本
-- 删除数据库 drop database if exists mybaits; -- 创建数据库 create database if not exists mybatis default character set utf8; -- 选择数据库 use mybatis; -- 删除数据表 drop table if exists student ; drop table if exists card; -- 创建数据表 create table card( cid int(255), num varchar(18), constraint pk_cid primary key (cid) ); create table student( sid int(255), sname varchar(32), scid int(255), constraint pk_sid primary key (sid), constraint fk_scid foreign key (scid) references card(cid) ); -- 增加测试数据 insert into card (cid,num) values(1,'123456789012345678'); insert into student (sid,sname,scid) values(1,'哈哈',1);
工具类MyBatis.java类
package util;
import java.io.IOException;
import java.io.Reader;
import java.sql.Connection;
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 MyBatisUtil {
private static ThreadLocal threadLocal = new ThreadLocal();
public static SqlSessionFactory sqlSessionFactory ;
//私有化构造方法
private MyBatisUtil(){}
//加载位于src/Mybatis.cfg.xml
static{
try {
Reader reader = Resources.getResourceAsReader("mybatis.cfg.xml");
sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSqlSession(){
//从当前线程中获取SqlSession对象
SqlSession sqlSession = threadLocal.get();
if(sqlSession == null){
if(sqlSessionFactory != null){
sqlSession = sqlSessionFactory.openSession();
//讲sqlSession与当前线程绑定在一起
threadLocal.set(sqlSession);
}
}
return sqlSession;
}
public static void closeSqlSession(){
//从当前线程中获取SqlSession对象
SqlSession sqlSession = threadLocal.get();
//如果SqlSession对象非空
if(sqlSession != null){
//关闭SqlSession对象
sqlSession.close();
//分离当前线程与SqlSession的关系
threadLocal.remove();
}
}
//测试
public static void main(String[] args) {
SqlSession sqlSession = MyBatisUtil.getSqlSession();
Connection conn= sqlSession.getConnection();
System.out.println(conn != null ?"连接成功":"连接失败");
}
}
mybatis.cfg.xml文件
Card.java和Student.java
package one2one;
import java.io.Serializable;
@SuppressWarnings("serial")
public class Card implements Serializable{
private Integer cid;
private String num;
public Integer getCid() {
return cid;
}
public void setCid(Integer cid) {
this.cid = cid;
}
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num;
}
}
package one2one;
import java.io.Serializable;
@SuppressWarnings("serial")
public class Student implements Serializable{
private Integer sid;
private String sname;
private Card card;
public Integer getSid() {
return sid;
}
public void setSid(Integer sid) {
this.sid = sid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public Card getCard() {
return card;
}
public void setCard(Card card) {
this.card = card;
}
}
Card.java的映射文件CardMapper.xml文件
Student.java类对应的映射文件StudentMapper.xml文件
select s.sid,s.sname,c.cid,c.num from student s,card c where s.scid = c.cid and s.sid = #{sid} select s.sid,s.sname,c.cid,c.num from student s,card c where s.scid = c.cid and s.sname = #{sname}
持久层类StudentCardDAO.java类
package one2one;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import util.MyBatisUtil;
public class StudentCardDAO {
public Student findById(Integer id) throws Exception{
SqlSession sqlSession = null;
try {
sqlSession = MyBatisUtil.getSqlSession();
return sqlSession.selectOne("studentNameSpace.findById", id);
} catch (Exception e) {
e.printStackTrace();
throw e;
}finally{
MyBatisUtil.closeSqlSession();
}
}
public Student findByName(String name) throws Exception{
SqlSession sqlSession = null;
try {
sqlSession = MyBatisUtil.getSqlSession();
return sqlSession.selectOne("studentNameSpace.findByName", name);
} catch (Exception e) {
e.printStackTrace();
throw e;
}finally{
MyBatisUtil.closeSqlSession();
}
}
//测试 查询1号学生的信息与身份证信息
@Test
public void testFindById() throws Exception{
StudentCardDAO dao = new StudentCardDAO();
Student student = dao.findById(1);
System.out.println(student.getSid()+":"+student.getSname()+":"+student.getCard().getNum());
}
//测试 查询“哈哈”学生的信息与身份证信息
@Test
public void testFindByName() throws Exception{
StudentCardDAO dao = new StudentCardDAO();
Student student = dao.findByName("哈哈");
System.out.println(student.getSid()+":"+student.getSname()+":"+student.getCard().getNum());
}
}
以上所述是小编给大家介绍的MyBatis一对一映射初识教程,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对考高分网网站的支持!



