Mybatis 接口方式对数据的增删改查 一对一关联查询

数据库中有两个表 student 和studentInfo

student表中的字段和数据

studentInfo表中的字段

ok数据库说完了,开始建立一个项目,对数据库中的数据进行操作吧

新建java项目,将mybatis的jar包和oracle数据库的访问包导入

建立几个需要用的包 entities, dao,util , test建立映射文件(.xml)和db.properties文件

db.properties:

mybatis-config.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">
<!-- mybatis配置的根标签 -->
<configuration>
    <properties resource="db.properties"></properties>
    <!--自动扫描实体类 -->
    <typeAliases>
        <package name="com.maya.entities" />
    </typeAliases>

    <!--default等于那个就执行那个 -->
    <environments default="test">
        <environment id="test">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}" />
                <property name="url" value="${jdbc}" />
                <property name="username" value="${user}" />
                <property name="password" value="${password}" />
            </dataSource>
        </environment>
    </environments>

<!-- 映射 -->
    <mappers>
        <package name="com.maya.dao" />
    </mappers>
</configuration>

这样,mybatis的配置文件配置完成,接下来写util文件(SqlSessionFactory)

package com.maya.util;

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 SqlSessionUtil {

    private static SqlSessionFactory sessionFactory;
    private static SqlSession session;

    public static SqlSession getSqlSession(){
        InputStream input=null;
        try {
            input=Resources.getResourceAsStream("mybatis-config.xml");
            sessionFactory=new SqlSessionFactoryBuilder().build(input);
            session=sessionFactory.openSession();
            input.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

        return session;
    }
}

接下来写实体类:需要注意的是,如果我们需要查student,需要把studentInfo表中的数据一起查出来的话,需要写出对应的关系;(篇幅原因,get/set和构造函数就不贴进来了)

Student

package com.maya.entities;

public class Student {
    private StudentInfo studentInfo;    //studentInfo的实体类
    private String sname;
    private String ssex;
    private Integer sclass;
    private Integer mark;
}

StudentInfo

package com.maya.entities;

import java.sql.Date;

public class StudentInfo {

    private Integer id;
    private Integer sno;
    private String saddress;
    private Date sbirthday;
}

实体类建立完成,接下来写接口,和xml文件

package com.maya.dao;

import java.util.List;

import com.maya.entities.StudentInfo;

public interface StudentInfoMapper {

    //查询所有
    public List<StudentInfo> select();

    //根据sno查询
    public StudentInfo selectbysno();
}
<?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="com.maya.dao.StudentInfoMapper">
  <!-- 查询整个studentInfo表 -->
      <select id="select" resultType="studentInfo">
          select * from studentinfo
      </select>
  </mapper>

建立一个junit测试用例

package com.maya.test;

import static org.junit.Assert.*;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.maya.dao.StudentInfoMapper;
import com.maya.entities.StudentInfo;
import com.maya.util.SqlSessionUtil;

public class TestJunit {

    private SqlSession session;
    private StudentInfoMapper sim;
    @Before
    public void setUp() throws Exception {
        //获取sqlsession 和StudentInfoMapper
        session=SqlSessionUtil.getSqlSession();
        sim=session.getMapper(StudentInfoMapper.class);
    }

    @After
    public void tearDown() throws Exception {
        session.commit();        //提交
        session.close();        //关闭
    }

    @Test
    public void test() {
        List<StudentInfo> list=sim.select();
        for(StudentInfo info:list){
            System.out.println(info);
        }
    }
}

执行结果如下

说明我们前面配置的没有问题

建立Student接口和配置文件

package com.maya.dao;

import java.util.List;
import java.util.Map;

import com.maya.entities.Student;

public interface StudentMapper {
    //查询出所有
    public List<Student> select();
    //多条件查询
    public List<Student> select(Map<String,Object> map);

}
<?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="com.maya.dao.StudentMapper">    <!--接口的限定名  -->

    <resultMap type="student" id="list">
        <association property="studentInfo" column="sno" select="com.maya.dao.StudentInfoMapper.selectbysno"/>
    </resultMap>

  <select id="select" resultMap="list">    <!--返回的值不是单一的表的值时用Map  -->
  select * from student s join studentinfo si on s.sno=si.sno
  </select>
  </mapper>

junit测试:

package com.maya.test;

import static org.junit.Assert.*;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.maya.dao.StudentInfoMapper;
import com.maya.dao.StudentMapper;
import com.maya.entities.Student;
import com.maya.entities.StudentInfo;
import com.maya.util.SqlSessionUtil;

public class TestJunit {

    private SqlSession session;
    private StudentInfoMapper sim;
    private StudentMapper sdm;
    @Before
    public void setUp() throws Exception {
        //获取sqlsession 和StudentInfoMapper
        session=SqlSessionUtil.getSqlSession();
        sim=session.getMapper(StudentInfoMapper.class);
        sdm=session.getMapper(StudentMapper.class);
    }

    @After
    public void tearDown() throws Exception {
        session.commit();        //提交
        session.close();        //关闭
    }

    @Test
    public void test() {
        List<Student> list=sdm.select();
        for(Student stu:list){
            System.out.println(stu);
        }

//        List<StudentInfo> list=sim.select();
//        for(StudentInfo info:list){
//            System.out.println(info);
//        }
//        

    }

}

结果如下

时间: 2024-08-13 01:40:45

Mybatis 接口方式对数据的增删改查 一对一关联查询的相关文章

Java操作Hbase进行建表、删表以及对数据进行增删改查,条件查询

1.搭建环境 新建JAVA项目,添加的包有: 有关Hadoop的hadoop-core-0.20.204.0.jar 有关Hbase的hbase-0.90.4.jar.hbase-0.90.4-tests.jar以及Hbase资源包中lib目录下的所有jar包 2.主要程序 Java代码 package com.wujintao.hbase.test; import java.io.IOException; import java.util.ArrayList; import java.util

Mybatis学习总结(二)—使用接口实现数据的增删改查

在这一篇中,让我们使用接口来实现一个用户数据的增删改查. 完成后的项目结构如下图所示: 在这里,person代表了一个用户的实体类.在该类中,描述了相关的信息,包括id.name.age.id_num信息.而personMapper则是该实体类的一个配置文件.需要注意的是,在上一篇博文中,namespace属性的值是其本身,而在这一篇中,使用的是接口.那么两者有什么区别呢?使用接口,那么相关的操作方法不用自己去实现,只需要调用该接口的相关的方法就能够实现相应的功能. 那么,在这里就有一个问题,接

通用DAO之MyBatis封装,封装通用的增删改查(二)

曾经发过一篇文章,大概写的就是阿海多么多么厉害,见到某位同事在Hibernate的基础上封装了一下,就以一己之力开发什么什么框架,最后写了个超大的一坨的事. 那么,后续篇来了.阿海不是自负之人,当之前的CRUD框架并没有达到理想的结果时,阿海转向了Mybatis封装.别问我为什么不是Hibernate.我本来就不喜欢Hibernate,即使在之前的一家公司一直被强制性的约束使用Hibernate时,也没有对Hibernate产生什么真正的好感,反而屡次发现了Hibernate的一些问题. 或许是

Node.js + MySQL 实现数据的增删改查

通过完成一个 todo 应用展示 Node.js + MySQL 增删改查的功能.这里后台使用 Koa 及其相应的一些中间件作为 server 提供服务. 初始化项目 $ mkdir node-crud && cd $_ $ yarn init -y && npx gitignore node 上面的命令创建了一个空文件夹 node-crud,进入之后初始化一个 package.json 以及创建 .gitignore 文件. 安装 Koa 并创建 app.js 以启动一个

yii中数据的"增删改查"相关工作!(此文比较乱,需细看)

使用findByPk()根据数据表主键查询的是对象,不需要使用foreach()循环出来 但是使用findall()和find()查询的是对象类型的数组需要使用foreach()循环出来 ======================================= public function getMinLimit () { $sql = "..."; $result = yii::app()->db->createCommand($sql); $query = $r

[实例]php中PDO方式实现数据库的增删改查

整理的比较容易理解的PDO操作实例,注意,需要开启php的pdo支持,php5.1以上版本支持实现数据库连接单例化,有三要素 静态变量.静态实例化方法.私有构造函数 DPDO.php //PDO操作类 //author http://www.lai18.com class DPDO{ private $DSN; private $DBUser; private $DBPwd; private $longLink; private $pdo; //私有构造函数 防止被直接实例化 private f

ios CoreData框架的使用,对上下文数据的增删改查,表与表之间的关联,1对多,1对1,谓词查询,多表连接

这里是只是代码,因为博客插入图片效果不是很好,我自己写的总结比较详细,有兴趣的朋友可以在评论里留下邮箱,我收到后会发给大家. 转载注明出处,重视原创者的劳动成果,谢谢! - (void)viewDidLoad { [super viewDidLoad]; [self _creatTable];//插入数据 //    [self _query];// 查询数据 // KVC很霸道,即使readonly通过kvc也可赋值,kvo精华 //    Book * book = [[Book alloc

数据的增删改查(三层)

进行数据操作必然少了对数据的增删改查,用代码生成器生成的代码不是那么满意!方便在今后使用,这里就主要写“数据访问层(Dal)” 注:这里由于是用于用于测试时,临时建的数据库用于测试使用,在实际使用过程中些许改点参数就可以使用了 /// <summary> /// 是否存在该记录 /// </summary> public bool Exists(long Id) { string sql = "select count(*) Name from t_temp where

jdbc增删改查,利用反射查询

整理自http://blog.csdn.net/yanzi1225627/article/details/26950615,谢谢作者! 本文我的爱点是: 1.利用反射实现数据库数据查询 2.编写一个sql语句,其中的参数用?来代替,然后将参数写到List里 例如使用例子: 1 String sql = "delete from userinfo where username = ?"; 2 List<Object> params = new ArrayList<Obj