初识Mybatis框架,实现增删改查等操作

简介: 此第一次接触Mybatis框架确实是有点不适应,特别是刚从Hibernate框架转转型过来,那么为什么要使用Mybatis框架,Mybatis框架和Hibernate框架又有什么异同呢? 这个问题在我的另一篇blogs中有专门的讲解,今天我主要是带着大家来探讨一下如何简单的使用Mybatis这个框...

此第一次接触Mybatis框架确实是有点不适应,特别是刚从Hibernate框架转转型过来,那么为什么要使用Mybatis框架,Mybatis框架和Hibernate框架又有什么异同呢?

这个问题在我的另一篇blogs中有专门的讲解,今天我主要是带着大家来探讨一下如何简单的使用Mybatis这个框架

可能有的朋友知道,Mybatis中是通过配置文件来实现这个的,这里面有很多的东西,我们就一点一点的讲吧

我们想要配置成功,首要的就是jar包,先从官网下载相应的jar包作为程序的支撑

有了jar包之后我么就来看看我们程序的主要的搭建

具体类的内容如下

Student Class

复制代码
package entity;
/*
 * 学生类
 * */
public class Student {
    //学生编号
    private Integer sid;
    //学生名称
    private String sname;
    //学生性别
    private String sex;
    
    
    
    
    
    
    
    
    
    
    public Student() {
    }
    public Student(String sname, String sex) {
        this.sname = sname;
        this.sex = sex;
    }
    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 String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    
}
复制代码

 

Grade Class

复制代码
package entity;
/*
 * 班级类
 * */
public class Grade {
    //班级编号
    private Integer gid;
    //班级名称
    private String gname;
    //班级描述
    private String gdesc;
    
    
    
    
    public Grade() {
    }
    public Grade(Integer gid, String gname, String gdesc) {
        this.gid = gid;
        this.gname = gname;
        this.gdesc = gdesc;
    }
    public Integer getGid() {
        return gid;
    }
    public void setGid(Integer gid) {
        this.gid = gid;
    }
    public String getGname() {
        return gname;
    }
    public void setGname(String gname) {
        this.gname = gname;
    }
    public String getGdesc() {
        return gdesc;
    }
    public void setGdesc(String gdesc) {
        this.gdesc = gdesc;
    }
    
}
复制代码

接下来我么就要配置我们的主要配置文件了,主要是指定我们要连接的数据库和具体连接操作

Configuration.xml

复制代码
<?xml version="1.0" encoding="UTF-8" ?>
<!--

       Copyright 2009-2012 the original author or authors.

       Licensed under the Apache License, Version 2.0 (the "License");
       you may not use this file except in compliance with the License.
       You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing, software
       distributed under the License is distributed on an "AS IS" BASIS,
       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
       See the License for the specific language governing permissions and
       limitations under the License.

-->
<!DOCTYPE configuration
    PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
<!-- 
  <settings>
    <setting name="useGeneratedKeys" value="false"/>
    <setting name="useColumnLabel" value="true"/>
  </settings>

  <typeAliases>
    <typeAlias alias="UserAlias" type="org.apache.ibatis.submitted.complex_property.User"/>
  </typeAliases> -->
  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC">
        <property name="" value=""/>
      </transactionManager>
      <dataSource type="UNPOOLED">
        <property name="driver" value="oracle.jdbc.OracleDriver"/>
        <property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl"/>
        <property name="username" value="practice"/>
        <property name="password" value="123"/>
      </dataSource>
    </environment>
  </environments>
  
   <mappers>
    <mapper resource="config/Student.xml"/>
  </mappers> 

</configuration>
复制代码

 

其实最主要的是如下图所示

 

到这里为止,所有的准备工作基本上就已经是完成了

接下来,使用Mybatis框架来实现我们的具体操作‘

1.查询所有学生信息

因为Mybatis是属于一种半自动化的框架技术所以呢sql是我们手动书写的,这也是Mybatis的一大特点

我们可以写出具体的实体配置文件

Student.xml

复制代码
<?xml version="1.0" encoding="UTF-8"?>
<!--

       Copyright 2009-2012 the original author or authors.

       Licensed under the Apache License, Version 2.0 (the "License");
       you may not use this file except in compliance with the License.
       You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing, software
       distributed under the License is distributed on an "AS IS" BASIS,
       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
       See the License for the specific language governing permissions and
       limitations under the License.

-->

<!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="Student">

  <resultMap type="entity.Student" id="StudentResult">
    <id column="sid" jdbcType="INTEGER" property="sid"/>
    <result column="sname" jdbcType="VARCHAR" property="sname"/>
    <result column="sex" jdbcType="VARCHAR" property="sex"/>
  </resultMap>
    
    <select id="selectAllStu"  resultMap="StudentResult">
        select * from Student
    </select>
 
</mapper>
复制代码

 

既然我们写了sql也指定了相应的实体类,那么我们到现在为止还并没有用到它,所以我们还需要在主配置文件中添加实体配置文件的引用

 

经过以上的步骤, 我们查询全部学生的配置文件基本上就已经完成了,现在我们来进行一道测试

复制代码
/*
     * 1.1 查询所有的学生信息
     * */
    @Test
    public void OneTest() throws Exception{
        //通过配置文件获取到数据库连接信息
        Reader reader = Resources.getResourceAsReader("config/Configuration.xml");
        //通过配置信息构建一个SessionFactory工厂
        SqlSessionFactory sqlsessionfactory=new SqlSessionFactoryBuilder().build(reader);
        //通过SessionFaction打开一个回话通道
        SqlSession session = sqlsessionfactory.openSession();
        //调用配置文件中的sql语句
        List<Student> list = session.selectList("Student.selectAllStu");
        //遍历查询出来的结果
        for (Student stu : list) {
            System.out.println(stu.getSname());
        }
        
        session.close();
    }
复制代码

执行之后的语句如下

这样我们使用Mybatis查询所有学生信息就完成了

 

2.带条件查询动态Sql拼接

复制代码
/*
     *1.2 带条件查询信息(动态Sql拼接)
     * */
    @Test
    public void selectAllStuByWhere() throws Exception{
        //通过配置文件获取到数据库连接信息
        Reader reader = Resources.getResourceAsReader("config/Configuration.xml");
        //通过配置信息构建一个SessionFactory工厂
        SqlSessionFactory sqlsessionfactory=new SqlSessionFactoryBuilder().build(reader);
        //通过SessionFaction打开一个回话通道
        SqlSession session = sqlsessionfactory.openSession();
        //准备一个学生对象作为参数
        Student student=new Student();
        student.setSname("3");
        //调用配置文件中的sql语句
        List<Student> list = session.selectList("Student.selectAllStuByWhere",student);
        //遍历查询出来的结果
        for (Student stu : list) {
            System.out.println(stu.getSname());
        }
        
        session.close();
    }
复制代码

 

 

小配置配置文件信息

复制代码
<?xml version="1.0" encoding="UTF-8"?>
<!--

       Copyright 2009-2012 the original author or authors.

       Licensed under the Apache License, Version 2.0 (the "License");
       you may not use this file except in compliance with the License.
       You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing, software
       distributed under the License is distributed on an "AS IS" BASIS,
       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
       See the License for the specific language governing permissions and
       limitations under the License.

-->

<!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="Student">

  <resultMap type="entity.Student" id="StudentResult">
    <id column="sid" jdbcType="INTEGER" property="sid"/>
    <result column="sname" jdbcType="VARCHAR" property="sname"/>
    <result column="sex" jdbcType="VARCHAR" property="sex"/>
  </resultMap>
    
    <!-- 简单查询所有信息 -->
     <select id="selectAllStu"  resultMap="StudentResult">
        select sid,sname,sex,gid from Student 
    </select> 
    
    <!--动态拼接Sql  -->
     <select id="selectAllStuByWhere" parameterType="entity.Student"  resultMap="StudentResult">
        select sid,sname,sex,gid from Student where 1=1
        <if test="sname!=null and !&quot;&quot;.equals(sname.trim())">
            and sname like '%'|| #{sname}|| '%' <!-- 模糊查询 -->
            <!-- and sname = #{sname} -->
        </if>
        
     </select>
</mapper>
复制代码

执行之后的结果就是

 

3.新增学生信息

复制代码
/*
     * 1.3 新增学生信息
     * 
     * */
    @Test
    public void InsertStuInfo() throws Exception{
        //通过配置文件获取配置信息
        Reader reader = Resources.getResourceAsReader("config/Configuration.xml");
        //构建一个SessionFactory,传入配置文件
        SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(reader);
        //获取session
        SqlSession session = factory.openSession();
        //准备参数对象
        Student stu=new Student();
        stu.setSname("巴黎的雨季");
        stu.setSex("男");
        //调用添加方法
        int count = session.insert("Student.InsertStuInfo", stu);
        if(count>0){
            System.out.println("添加成功");
        }else{
            System.out.println("添加失败");
        }
        //提交
        session.commit();
        //关闭
        session.close();
    }
复制代码

 

在小配置中增加一个节点

<!-- 新增学生信息 -->
     <insert id="InsertStuInfo" parameterType="entity.Student" >
         insert into Student values(SEQ_NUM.Nextval,#{sname},#{sex},1)
     </insert>

执行之后结果为

后续的删除和修改代码基本上和新增是一致的,只是调用的sql语句不同,所以后续我就不做详细的解释了,只将代码摆出来,详细大家都能够看得明白!!

 

4.删除学生信息根据id

复制代码
/*
     * 1.4根据SID删除学生信息
     * */
    @Test
    public void DeleteStuBySid()throws Exception{
        //通过配置文件获取配置信息
        Reader reader = Resources.getResourceAsReader("config/Configuration.xml");
        //构建一个SessionFactory,传入配置文件
        SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(reader);
        //获取session
        SqlSession session = factory.openSession();
        //准备参数
        int sid=2;
        //调用删除方法
        int count = session.delete("Student.DeleteStuBySid", sid);
        if(count>0){
            System.out.println("删除成功");
        }else{
            System.out.println("删除失败");
        }
        //提交
        session.commit();
        //关闭
        session.close();
    }
复制代码

 

需要在配置文件中新增的是

 <!-- 删除学生信息 -->
     <insert id="DeleteStuBySid" parameterType="int">
         delete from Student where sid=#{sid}
     <!--或者是     delete from Student where sid=#{_parameter} -->
     </insert>

 

5.根据SID修改学生信息

复制代码
/*
     * 1.5根据SID修改学生信息
     * 
     * */
    @Test
    public void UpdateStuBySid()throws Exception{
        //通过配置文件获取配置信息
        Reader reader = Resources.getResourceAsReader("config/Configuration.xml");
        //构建一个SessionFactory,传入配置文件
        SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(reader);
        //获取session
        SqlSession session = factory.openSession();
        //准备参数对象
        Student stu=new Student();
        stu.setSid(1);
        stu.setSname("绿茵");
        stu.setSex("女");
        //调用删除方法
        int count = session.update("Student.UpdateStuBySid", stu);
        if(count>0){
            System.out.println("修改成功");
        }else{
            System.out.println("修改失败");
        }
        //提交
        session.commit();
        //关闭
        session.close();
    }
复制代码

 

需要在配置文件中添加的是

 <!-- 根据SID修改学生信息 -->
     <update id="UpdateStuBySid" parameterType="entity.Student" >
         update Student set sname=#{sname},sex=#{sex} where sid=#{sid}
     </update>

 

 

以上我们就简单的完成了对Mybatis的增、删、改、查的基本操作了,关于Mybatis的一些高级内容的讲解我会继续在后中为大家持续讲解

 

http://www.cnblogs.com/liujiayun/p/5807425.html

 

相关文章
SQL XML Java
115 0
|
3月前
|
SQL Java 数据库连接
区分iBatis与MyBatis:两个Java数据库框架的比较
总结起来:虽然从技术角度看,iBATIS已经停止更新但仍然可用;然而考虑到长期项目健康度及未来可能需求变化情况下MYBATISS无疑会是一个更佳选择因其具备良好生命周期管理机制同时也因为社区力量背书确保问题修复新特征添加速度快捷有效.
236 12
|
4月前
|
SQL XML Java
MyBatis框架如何处理字符串相等的判断条件。
总的来说,MyBatis框架提供了灵活而强大的机制来处理SQL语句中的字符串相等判断条件。无论是简单的等值判断,还是复杂的条件逻辑,MyBatis都能通过其标签和属性来实现,使得动态SQL的编写既安全又高效。
301 0
|
9月前
|
人工智能 Java 数据库连接
MyBatis Plus 使用 Service 接口进行增删改查
本文介绍了基于 MyBatis-Plus 的数据库操作流程,包括配置、实体类、Service 层及 Mapper 层的创建。通过在 `application.yml` 中配置 SQL 日志打印,确保调试便利。示例中新建了 `UserTableEntity` 实体类映射 `sys_user` 表,并构建了 `UserService` 和 `UserServiceImpl` 处理业务逻辑,同时定义了 `UserTableMapper` 进行数据交互。测试部分展示了查询、插入、删除和更新的操作方法及输出结果,帮助开发者快速上手 MyBatis-Plus 数据持久化框架。
671 0
|
9月前
|
Oracle 关系型数据库 Java
|
9月前
|
SQL 缓存 Java
框架源码私享笔记(02)Mybatis核心框架原理 | 一条SQL透析核心组件功能特性
本文详细解构了MyBatis的工作机制,包括解析配置、创建连接、执行SQL、结果封装和关闭连接等步骤。文章还介绍了MyBatis的五大核心功能特性:支持动态SQL、缓存机制(一级和二级缓存)、插件扩展、延迟加载和SQL注解,帮助读者深入了解其高效灵活的设计理念。
|
9月前
|
XML Java 数据库连接
二、搭建MyBatis采用xml方式,验证CRUD(增删改查操作)
二、搭建MyBatis采用xml方式,验证CRUD(增删改查操作)
307 21
|
11月前
|
SQL Java 数据库连接
对Spring、SpringMVC、MyBatis框架的介绍与解释
Spring 框架提供了全面的基础设施支持,Spring MVC 专注于 Web 层的开发,而 MyBatis 则是一个高效的持久层框架。这三个框架结合使用,可以显著提升 Java 企业级应用的开发效率和质量。通过理解它们的核心特性和使用方法,开发者可以更好地构建和维护复杂的应用程序。
618 29
|
SQL Java 数据库连接
持久层框架MyBatisPlus
持久层框架MyBatisPlus
301 1
持久层框架MyBatisPlus
|
缓存 Cloud Native 安全
探索阿里巴巴新型ORM框架:超越MybatisPlus?
【10月更文挑战第9天】在Java开发领域,Mybatis及其增强工具MybatisPlus长期占据着ORM(对象关系映射)技术的主导地位。然而,随着技术的发展,阿里巴巴集团推出了一种新型ORM框架,旨在提供更高效、更简洁的开发体验。本文将对这一新型ORM框架进行探索,分析其特性,并与MybatisPlus进行比较。
592 0