MyBatis的增删改查。
数据库的经典操作:增删改查。
在这一章我们主要说明一下简单的查询和增删改,并且对程序接口做了一些调整,以及对一些问题进行了解答。
1、调整后的结构图:

2、连接数据库文件配置分离:
一般的程序都会把连接数据库的配置单独放在.properties 文件中,然后在XML文件中引用,示例如下:
config.properties:
driver=oracle.jdbc.OracleDriver
url=jdbc:oracle:thin:@127.0.0.1:1521:orcl
username=phonesurvey
password=world
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">
<configuration>
<properties resource="config.properties" />
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="nankang/dao/agentDao.xml" />
</mappers>
</configuration>


3、SqlSession分离:
SqlSeesion单独做成工具类,以便调用,示例如下:
SqlSessionHelper:


package nankang.util; import java.io.InputStream; import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class SqlSessionHelper { public static SqlSessionFactory getSessionFactory(){
SqlSessionFactory sessionFactory = null;
String resource= "mybatis-config.xml";
try{
InputStream inputStream = Resources.getResourceAsStream(resource);
//Reader reader = Resources.getResourceAsReader(resource);
sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}catch(Exception ex){
ex.printStackTrace();
}
return sessionFactory;
}
}


SqlSessionFactory创建时,根据Reader和InputStream都可以。
4、XML文件添加内容:
agentDao.xml:


<?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="nankang.dao.AgentDao">
<!-- 根据Id查询 -->
<select id="selectAgentById" parameterType="string" resultType="nankang.po.Agent">
select * from Agent where AgentId=#{id}
</select>
<!-- 添加 -->
<insert id="insertAgent" parameterType="nankang.po.Agent">
insert into Agent(agentId, companyCode, LoginName, AgentPwd, AgentCode, Name, status,sysFlag)
values(#{agentId},'SHNK',#{loginName},'D41D8CD98F00B204E9800998ECF8427E',#{agentCode},#{name},1,1)
</insert>
<!-- 删除 -->
<delete id="deleteAgent" parameterType="string">
delete from Agent where agentid=#{id}
</delete>
<!-- 修改 -->
<update id="updateAgent" parameterType="nankang.po.Agent">
update agent set name=#{name} where agentid=#{agentId}
</update>
<!-- 查询所有 -->
<select id="selectAllAgent" resultType="nankang.po.Agent">
select * from Agent
</select>
<!-- 查询所有无返回对象 -->
<select id="selectAllAgent2" resultType="hashmap">
select * from Agent
</select> </mapper>


AgentDao.java:


package nankang.dao; import java.util.List;
import java.util.Map; import nankang.po.Agent; import org.apache.ibatis.annotations.Select; public interface AgentDao {
//根据Id查询
public Agent selectAgentById(String Id);
//根据名称查询
@Select("select * from Agent where name=#{name}")
public Agent selectAgentByName(String name);
//添加
public int insertAgent(Agent agent);
//删除
public int deleteAgent(String id);
//修改
public int updateAgent(Agent agent);
//查询所有的
public List<Agent> selectAllAgent();
public List<Map<String, Object>> selectAllAgent2(); }


1、XML文件中的语句,可以直接写在接口文件中,如:根据名称查询;
2、其他参考示例。
几个问题说明:
1)如何查询数据集合?
使用ResultType设置,返回用List<T>即可
2)查询一条数据,如果为空,怎么判断?
如果没有查询到数据,返回为NULL,进行空对象判断即可
3)查询所有的集合,不放在构建对象的List中:
4)如何实现事务:
SqlSession:commit,rollback,close
5、测试


package nankang.test; import java.util.List;
import java.util.Map; import nankang.dao.AgentDao;
import nankang.util.SqlSessionHelper; import org.apache.ibatis.session.SqlSession; public class test { /**
* @param args
*/
public static void main(String[] args) { SqlSession sqlSession = SqlSessionHelper.getSessionFactory().openSession();
try{ AgentDao agentMapper = sqlSession.getMapper(AgentDao.class); //根据Id查询
// Agent agent = agentMapper.selectAgentById("SHNKAG00000000051");
// if(null != agent){
// System.out.println(agent.getName());
// }else{
// System.out.println("不存在该用户");
// }
// agent = agentMapper.selectAgentByName("1001");
// System.out.println(agent.getAgentId());
//查询所有
List<Map<String, Object>> agentList = agentMapper.selectAllAgent2();
System.out.println(agentList.size());
//添加
// Format format = new SimpleDateFormat("00yyyyMMddhhmmss");
// Calendar calendar = Calendar.getInstance();
// String dateStr = format.format(calendar.getTime());
// Agent agent = new Agent();
// agent.setAgentId(dateStr);
// agent.setLoginName("1111");
// agent.setAgentCode("aaaa");
// agent.setName("aaaa");
// int num = agentMapper.insertAgent(agent);
// System.out.println(num);
//删除
// int num = agentMapper.deleteAgent("0020150226093127");
// System.out.println(num);
//更新
// Agent agent = new Agent();
// agent.setAgentId("0020150226010005");
// agent.setName("Test");
// int num = agentMapper.updateAgent(agent);
// System.out.println(num); //增删改,提交
sqlSession.commit();
System.out.println("完成");
}catch(Exception ex){
sqlSession.rollback();
System.out.println(ex.getMessage());
}finally{
sqlSession.close();
} } }


这边需要注意的是:SqlSession一定要close
MyBatis的增删改查。的更多相关文章
- 学习MyBatis必知必会(5)~了解myBatis的作用域和生命周期并抽取工具类MyBatisUtil、mybatis执行增删改查操作
一.了解myBatis的作用域和生命周期[错误的使用会导致非常严重的并发问题] (1)SqlSessionFactoryBuilder [ 作用:仅仅是用来创建SqlSessionFactory,作用 ...
- MyBatis批量增删改查操作
前文我们介绍了MyBatis基本的增删该查操作,本文介绍批量的增删改查操作.前文地址:http://blog.csdn.net/mahoking/article/details/43673741 ...
- 上手spring boot项目(三)之spring boot整合mybatis进行增删改查的三种方式。
1.引入依赖. <!--springboot的web起步依赖--><dependency> <groupId>org.springframework.boot< ...
- 上手spring boot项目(三)之spring boot整合mybatis进行增删改查
使用mybatis框架进行增删改查大致有两种基础方式,一种扩展方式.两种基础方式分别是使用xml映射文件和使用方法注解.扩展方式是使用mybatis-plus的方式,其用法类似于spring-data ...
- 从0开始完成SpringBoot+Mybatis实现增删改查
1.准备知识: 1)需要掌握的知识: Java基础,JavaWeb开发基础,Spring基础(没有Spring的基础也可以,接触过Spring最好),ajax,Jquery,Mybatis. 2)项目 ...
- Spring Boot入门系列(六)如何整合Mybatis实现增删改查
前面介绍了Spring Boot 中的整合Thymeleaf前端html框架,同时也介绍了Thymeleaf 的用法.不清楚的朋友可以看看之前的文章:https://www.cnblogs.com/z ...
- Mybatis实例增删改查(二)
创建实体类: package com.test.mybatis.bean; public class Employee { private Integer id; private String las ...
- mybatis的增删改查返回值小析(六)
本文验证了通过mybatis访问数据库时的,增删改查的返回值情况. 直接看代码. 1.service层 /** *@Author: Administrator on 2020/3/12 15:15 * ...
- ssm 框架实现增删改查CRUD操作(Spring + SpringMVC + Mybatis 实现增删改查)
ssm 框架实现增删改查 SpringBoot 项目整合 一.项目准备 1.1 ssm 框架环境搭建 1.2 项目结构图如下 1.3 数据表结构图如下 1.4 运行结果 二.项目实现 1. Emplo ...
随机推荐
- 超精简易用cocoaPods的安装和使用
cocoaPods 安装和使用 第一步:替换ruby源 $ gem sources -l 查看当前ruby的源 $ gem sources ...
- Struts优缺点
跟Tomcat.Turbine等诸多Apache项目一样,是开源软件,这是它的一大优点.使开发者能更深入的了解其内部实现机制. Struts开放源码框架的创建是为了使开发者在构建基于Java Serv ...
- 17.QT-事件处理分析、事件过滤器、拖放事件
Qt事件处理介绍 Qt平台会将系统产生的消息转换为Qt事件 Qt事件是一个QEvent的对象 Qt事件用来描述程序内部或外部发生的动作 任意的QObject对象都具备事件处理的能力 Qt常见的事件继承 ...
- 【转载】Session的生命周期
http://www.cnblogs.com/binger/archive/2013/03/19/2970171.html 以前在学习的时候没怎么注意,今天又回过头来仔细研究研究了一下Session的 ...
- WebAPP移动前端性能优化规范和设计指导
- 当今商业中使用的三种十分重要的IT应用系统
本文为读书笔记,其中内容摘自<信息时代的管理信息系统>第八版第二章 当今商业中使用的三种十分重要的IT应用系统: 供应链管理(SCM) 客户关系管理(CRM) 电子协同(e-collabo ...
- Java虚拟机-内存tips
java虚拟机内存可以分为独占区和共享区. 独占区:虚拟内存栈.本地方法栈.程序计数器. 共享区:方法区.Java堆(用来存放对象实例). 程序计数器 比较小的内存空间,当前线程所执行的字节码的行号指 ...
- 大型三甲医院医疗体检信息管理系统源码 PEIS 体检科软件 CS
详情请点击查看 开发环境 :VS2008 + C# + SQL2000 功能介绍: 1:设置:操作员设置 系统功能设置 用户组权限设置 公告打印设置 数据字典设置 临床类型设置 体检 ...
- dw cs6 trial
试用版: https://helpx.adobe.com/x-productkb/policy-pricing/cs6-product-downloads.html English/Japanese: ...
- tomcat项目绑定到域名及运行内存配置
一.tomcat中的项目绑定到域名通过域名访问 1.在tomcat下的conf/server.xml中找到Host修改(1.name为你的域名,2.配置Context中的path为空就是直接访问项目不 ...