此第一次接触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 - 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=""/>
</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 - 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("");
//调用配置文件中的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 - 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 =
<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>){
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},)
</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=;
//调用删除方法
int count = session.delete("Student.DeleteStuBySid", sid);
if(count>){
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();
stu.setSname("绿茵");
stu.setSex("女");
//调用删除方法
int count = session.update("Student.UpdateStuBySid", stu);
if(count>){
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 Student
<set>
<if test="sname!=null">
sname=#{sname},
</if>
<if test="sex!=null">
sex=#{sex},
</if>
</set>
where sid=#{sid}
</update>

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

初识Mybatis框架,实现增删改查等操作(动态拼接和动态修改)的更多相关文章

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

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

  2. ssm 框架实现增删改查CRUD操作(Spring + SpringMVC + Mybatis 实现增删改查)

    ssm 框架实现增删改查 SpringBoot 项目整合 一.项目准备 1.1 ssm 框架环境搭建 1.2 项目结构图如下 1.3 数据表结构图如下 1.4 运行结果 二.项目实现 1. Emplo ...

  3. spring boot整合mybatis框架及增删改查(jsp视图)

    工具:idea.SQLyog 版本:springboot1.5.9版本.mysql5.1.62 第一步:新建项目 第二步:整合依赖(pom.xml) <dependencies> < ...

  4. Mybatis实现简单增删改查

    Mybatis的简单应用 学习内容: 需求 环境准备 代码 总结: 学习内容: 需求 使用Mybatis实现简单增删改查(以下是在IDEA中实现的,其他开发工具中,代码一样) jar 包下载:http ...

  5. tp框架的增删改查

    首先,我们来看一下tp框架里面的查询方法: 查询有很多种,代码如下: <?php namespace Admin\Controller; use Think\Controller; class ...

  6. Yii2.0高级框架数据库增删改查的一些操作(转)

    yii2.0框架是PHP开发的一个比较高效率的框架,集合了作者的大量心血,下面通过用户为例给大家详解yii2.0高级框架数据库增删改查的一些操作 --------------------------- ...

  7. Yii2.0高级框架数据库增删改查的一些操作

    yii2.0框架是PHP开发的一个比较高效率的框架,集合了作者的大量心血,下面通过用户为例给大家详解yii2.0高级框架数据库增删改查的一些操作 --------------------------- ...

  8. MyBatis简单的增删改查以及简单的分页查询实现

    MyBatis简单的增删改查以及简单的分页查询实现 <? xml version="1.0" encoding="UTF-8"? > <!DO ...

  9. Entity - 使用EF框架进行增删改查 - 模型先行

    模型先行:先创建数据库实体模型,然后再进行数据库的增删改查. 基本步骤是不变的,可参照 <Entity - 使用EF框架进行增删改查 - 数据库先行> 其中的不同是,在创建数据库实体模型的 ...

随机推荐

  1. ABP框架理论学习之后台工作(Jobs)和后台工作者(Workers)

    返回总目录 本篇目录 介绍 后台工作 后台工作者 让你的应用程序一直运行 介绍 ABP提供了后台工作和后台工作者,它们会在应用程序的后台线程中执行一些任务. 后台工作 后台工作以队列和持续的方式在后台 ...

  2. ASP.NET MVC 路由(五)

    ASP.NET MVC 路由(五) 前言 前面的篇幅讲解了MVC中的路由系统,只是大概的一个实现流程,让大家更清晰路由系统在MVC中所做的以及所在的位置,通过模糊的概念描述.思维导图没法让您看到路由的 ...

  3. linux下使用adb连接android手机

    一.新建文件 cat /etc/udev/rules.d/51-android.rules SUBSYSTEM==" 二.重启 udev sudo /etc/init.d/udev rest ...

  4. 修改注册表 去除Windows快捷方式图标小箭头

    一些朋友不喜欢Windows系统中快捷方式图标上面的小箭头,下面介绍如何修改注册表去除快捷方式图标上的小箭头. 1.开始->运行->输入regedit,启动注册表编辑器,然后; 2.依次展 ...

  5. Android笔记——提升ListView的运行效率

    之所以说 ListView 这个控件很难用,就是因为它有很多的细节可以优化,其中运行效率就是很重要的一点.目前我们ListView 的运行效率是很低的,因为在 FruitAdapter 的getVie ...

  6. $watch $apply and $evalAsync vs $timeout

    $watch $scope对象上的$watch方法会给Angular事件循环内的每个$digest调用装配一个脏值检查. 如果在表达式上检测到变化, Angular总是会返回$digest循环. $w ...

  7. 推荐12个漂亮的 CSS3 按钮实现方案

    在过去,我们都是使用图片或者JavaScript来实现漂亮的按钮效果,随着越来越多的浏览器对CSS3的支持和完善,使用CSS3来实现美观的按钮已没有太多的障碍.今天,本文收集了12个很不错的CSS3按 ...

  8. JAVA的静态变量、静态方法、静态类

    静态变量和静态方法都属于静态对象,它与非静态对象的差别需要做个说明. (1)Java静态对象和非静态对象有什么区别? 比对如下: 静态对象                                ...

  9. 【原创】开源Math.NET基础数学类库使用(11)C#计算相关系数

                   本博客所有文章分类的总目录:[总目录]本博客博文总目录-实时更新  开源Math.NET基础数学类库使用总目录:[目录]开源Math.NET基础数学类库使用总目录 前言 ...

  10. javascript模拟继承

    javascript作为前端开发的标配技能,如果不掌握好它的三大特点:1.原型 2.作用域 3. 闭包 ,又怎么可以说你学好了这门语言呢?如果标配的技能都没有撑握好,怎么可以任性的玩耍呢?怎么验证自己 ...