SpringBoot(二十二)整合Mybatis,使用SqlSessionTemplate实现增删改查[通俗易懂]

SpringBoot(二十二)整合Mybatis,使用SqlSessionTemplate实现增删改查[通俗易懂]在之前这篇基础上进行改造使用JdbcTemplate实现增删改查。SpringBoot版本:2.1.1目录结构如下:pom文件添加依赖,如下:<!–添加依赖以后Mybatis就自动配置好了,可以直接使用,具体自动配置代码到mybatis-spring-boot-autoconfigure包下查看–><!–上一篇博客里添加的spring-boot…

大家好,又见面了,我是你们的朋友全栈君。

在之前这篇基础上进行改造使用JdbcTemplate实现增删改查

SpringBoot版本:2.1.1

目录结构如下:

SpringBoot(二十二)整合Mybatis,使用SqlSessionTemplate实现增删改查[通俗易懂]

pom文件添加依赖,如下:

<!-- 添加依赖以后Mybatis就自动配置好了,可以直接使用,具体自动配置代码到mybatis-spring-boot-autoconfigure包下查看 -->
<!-- 上一篇博客里添加的spring-boot-starter-jdbc的依赖也可以去掉了,在这个里面已经有了,去不去掉都不影响(个人强迫症,哈哈哈) -->

<dependency>
	<groupId>org.mybatis.spring.boot</groupId>
	<artifactId>mybatis-spring-boot-starter</artifactId>
	<version>1.1.1</version>
</dependency>

配置文件application.properties里添加配置,如下:

#设置一下日志级别和格式,等会看sql打印
logging.level.com.eastcom.sql=debug
logging.pattern.console=%d{HH:mm:ss.SSS}  %-5p %c - %m%n

# 指定mapper.xml所在位置
mybatis.mapper-locations=classpath:mapper/*.xml

 实体类还是不变,新加一个example类,该类是Mybatis generator自动生成的,将context标签中的targetRuntime设置”MyBatis3″就行了。这里就不贴该类了,mapper.xml这里也不贴了,都是自动生成的,这里贴一下Mybatis generator的代码,生成以后放到对应的目录下就可以了

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
  PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
  "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>

	<!-- JDBC连接驱动JAR包 -->
	<classPathEntry location="E:\MyFile\mybatisRun\ojdbc6-11.2.0.3.jar" />

	<context id="OracleTables" targetRuntime="MyBatis3">

		<!-- 取消生成的代码注释 -->
		<commentGenerator>
			<property name="suppressAllComments" value="true" />
		</commentGenerator>
	
		<jdbcConnection 
			driverClass="oracle.jdbc.driver.OracleDriver"
			connectionURL="jdbc:oracle:thin:localhost:scott" 
			userId="scott"	
			password="tiger" />
			
		<!-- 类型转换器 -->
		<javaTypeResolver>
			<property name="forceBigDecimals" value="false" />
		</javaTypeResolver>
		
		<!--生成实体类,targetProject:自动生成代码的位置,targetPackage:包名 -->
		<javaModelGenerator targetPackage="com.eastcom.sql.bean" targetProject="GenertorTest">
			<property name="enableSubPackages" value="true" />
			<property name="trimStrings" value="false" />
		</javaModelGenerator>
		
		<!-- 生成mapper.xml -->
		<sqlMapGenerator targetPackage="com.eastcom.sql.bean" targetProject="GenertorTest">
			<property name="enableSubPackages" value="true" />
		</sqlMapGenerator>
		
		<!-- tableName:用于自动生成代码的数据库表;domainObjectName:对应于数据库表的javaBean类名 -->
		<table tableName="Dept" 
		domainObjectName="Dept"></table>
	</context>

</generatorConfiguration>

 然后dao层,接口这里就不需要了,新增一个类BaseDao,作为所有dao的基类,该类封装了mapper.xml里对应的方法,代码如下:

package com.eastcom.sql.dao;

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

import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.exceptions.TooManyResultsException;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.MyBatisSystemException;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

/**
 *  Record:实体类,Example:generator生成的用于拼接where条件的帮助类,可以在不修改mapper文件的基础上添加where条件
 *  下面NameSpace后面 + 的是mapper文件里的标签id。
 */
public class BaseDao<Record, Example> {
	
	protected String NameSpace = this.getClass().getName() + ".";
	
	@Autowired
	protected SqlSessionTemplate sqlSessionTemplate;
	
	/**
	 * count(*)
	 */
	public int countByExample(Example example) {
		Integer count = this.sqlSessionTemplate.selectOne(NameSpace
				+ "countByExample", example);
		return count.intValue();
	}
	
	/**
	 * 删除
	 */
	@Transactional(rollbackFor=Exception.class)
	public int deleteByExample(Example example) {
		return this.sqlSessionTemplate.delete(NameSpace + "deleteByExample",
				example);
	}
	
	/**
	 * 查询,不带分页
	 */
	public List<Record> selectByExample(Example example) {
		return sqlSessionTemplate.selectList(NameSpace + "selectByExample",
				example);
	}
	
	/**
	 * 查一条数据
	 */
	@SuppressWarnings("unchecked")
	public Record selectOneByExample(Example example) {
		try{
		return sqlSessionTemplate.selectOne(NameSpace + "selectByExample",
				example);
		}catch(MyBatisSystemException e){
			if(e.getRootCause() instanceof TooManyResultsException)
				return (Record) sqlSessionTemplate.selectList(NameSpace + "selectByExample",
					example).get(0);
			else
				throw e;
		}
	}
	
	/**
	 * 根据主键查一条数据
	 */
	public Record selectByPrimaryKey(Object key){
		return sqlSessionTemplate.selectOne(NameSpace+"selectByPrimaryKey", key);
	}
	
	/**
	 * 修改record中有值的字段 
	 */
	@Transactional(rollbackFor=Exception.class)
	public int updateByExampleSelective(@Param("record") Record record,
			@Param("example") Example example) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("record", record);
		map.put("example", example);
		return this.sqlSessionTemplate.update(NameSpace
				+ "updateByExampleSelective", map);
	}
	
	/**
	 * 全量修改
	 */
	@Transactional(rollbackFor=Exception.class)
	public int updateByExample(@Param("record") Record record,
			@Param("example") Example example) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("record", record);
		map.put("example", example);
		return this.sqlSessionTemplate.update(NameSpace + "updateByExample",
				map);
	}
	
	/**
	 * 全量新增
	 */
	@Transactional(rollbackFor=Exception.class)
	public int insert(Record record) {
		return sqlSessionTemplate.insert(NameSpace + "insert", record);
	}
	
	/**
	 * 仅新增record中有值的列
	 */
	@Transactional(rollbackFor=Exception.class)
	public int insertList(List<Record> record) {
		SqlSession session = sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH, false);
		for(Record rec : record)
			sqlSessionTemplate.insert(NameSpace + "insertSelective", rec);
		session.commit();		
		return 1;
	}
	
	/**
	 * 同上,新增
	 */
	@Transactional(rollbackFor=Exception.class)
	public int insertSelective(Record record) {
		return sqlSessionTemplate.insert(NameSpace + "insertSelective", record);
	}
}

 然后DeptDao继承BaseDao,里面就什么都不用写了,方法都在父类里。

package com.eastcom.sql.dao;

import org.springframework.stereotype.Repository;

import com.eastcom.sql.bean.Dept;
import com.eastcom.sql.bean.DeptExample;

@Repository
public class DeptDao extends BaseDao<Dept, DeptExample> {

}

最后修改DetpController,service这里就不要了。原来jdbcTemplate的代码注释了,对比一下,其实controller里改的不多,就四行代码。

package com.eastcom.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.eastcom.controller.util.JsonResult;
import com.eastcom.controller.util.ParamDto;
import com.eastcom.controller.util.Status;
import com.eastcom.service.DeptService;
import com.eastcom.sql.bean.Dept;
import com.eastcom.sql.bean.DeptExample;
import com.eastcom.sql.dao.DeptDao;

@Controller
@RequestMapping("/jdbc")
public class DetpController {
	
	@Autowired
	private DeptDao deptDao;
	
	@RequestMapping(value="/select",method=RequestMethod.GET)
	public ResponseEntity<JsonResult> selectById(Integer id){
		JsonResult result = new JsonResult();
		try {
			Dept data = deptDao.selectByPrimaryKey(id);
//			Dept data = deptService.selectById(id);
			result.setData(data);
			result.setStatus(Status.OK);
		} catch (Exception e) {
			result.setStatus(Status.ERROR);
			result.setData(e.getClass()+":"+e.getMessage());
			e.printStackTrace();
		}
		return ResponseEntity.ok(result); 
	}
	
	//@RequestBody:把接收到的json字符串自动转换为所对应的对象
	/**
	 * @param dept  { "deptno":"60", "dname":"开发", "location":"上海" }
	 * @return
	 */
	@PostMapping(value="/insert")
	public ResponseEntity<JsonResult> insert(@RequestBody Dept dept){
		JsonResult result = new JsonResult();
		try {
			Integer insert = deptDao.insertSelective(dept);
//			Integer insert = deptService.insert(dept);
			result.setData(insert);
			result.setStatus(Status.OK);
		} catch (Exception e) {
			result.setStatus(Status.ERROR);
			result.setData(e.getClass()+":"+e.getMessage());
			e.printStackTrace();
		}
		return ResponseEntity.ok(result); 
	}
	
	@PostMapping(value="/update")
	public ResponseEntity<JsonResult> update(@RequestBody ParamDto dto){
		JsonResult result = new JsonResult();
		try {
			System.out.println("dto:"+ dto.toString());
			
			DeptExample example = new DeptExample();
			example.createCriteria().andDeptnoEqualTo(dto.getId());
			Integer update = deptDao.updateByExampleSelective(dto.getDept(), example);
			
//			Integer update = deptService.updateById(dto.getId(),dto.getDept());
			result.setData(update);
			result.setStatus(Status.OK);
		} catch (Exception e) {
			result.setStatus(Status.ERROR);
			result.setData(e.getClass()+":"+e.getMessage());
			e.printStackTrace();
		}
		return ResponseEntity.ok(result); 
	}
	
	@PostMapping(value="/delete")
	public ResponseEntity<JsonResult> delete(@RequestParam("id") String id,HttpServletRequest request){
		JsonResult result = new JsonResult();
		try {
			DeptExample example = new DeptExample();
			example.createCriteria().andDeptnoEqualTo(Integer.parseInt(id));
			Integer delete = deptDao.deleteByExample(example);
			
//			Integer delete = deptService.deleteById(Integer.parseInt(id));
			result.setData(delete);
			result.setStatus(Status.OK);
		} catch (Exception e) {
			result.setStatus(Status.ERROR);
			result.setData(e.getClass()+":"+e.getMessage());
			e.printStackTrace();
		}
		return ResponseEntity.ok(result); 
	}

}

启动类还是那样,不变,启动来试一下。

查询:

SpringBoot(二十二)整合Mybatis,使用SqlSessionTemplate实现增删改查[通俗易懂]

SpringBoot(二十二)整合Mybatis,使用SqlSessionTemplate实现增删改查[通俗易懂]

新增:

SpringBoot(二十二)整合Mybatis,使用SqlSessionTemplate实现增删改查[通俗易懂]

SpringBoot(二十二)整合Mybatis,使用SqlSessionTemplate实现增删改查[通俗易懂]

修改:

SpringBoot(二十二)整合Mybatis,使用SqlSessionTemplate实现增删改查[通俗易懂]

SpringBoot(二十二)整合Mybatis,使用SqlSessionTemplate实现增删改查[通俗易懂]

删除:

SpringBoot(二十二)整合Mybatis,使用SqlSessionTemplate实现增删改查[通俗易懂]

SpringBoot(二十二)整合Mybatis,使用SqlSessionTemplate实现增删改查[通俗易懂]

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/141635.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • linux 内存信息_shell查看内存使用情况

    linux 内存信息_shell查看内存使用情况pmaplddstace要熟悉的几个调试命令!两个查看内存的文件$cat/proc/&lt;pid&gt;/stat|awk'{print$23/1024}’$cat/proc/&lt;pid&gt;/status|grep-ivmsize其中,关于内存的是VSZ和RSS这两个概念manps看看它们的含义:rss       RSS    resident…

    2025年7月7日
    1
  • 【LDC1314】电感传感器中文手册与检测原理介绍

    【LDC1314】电感传感器中文手册与检测原理介绍关键词:LDC1314,电感传感器,金属传感器,中文手册【声明:本博文参考TI官方手册翻译而成,旨在帮助大家快速了解这款芯片,如翻译有误欢迎评论指出,转载需注明来源!】以下是我对TI官方手册的人肉翻译,截取了其中的关键部分,有助于大家更好的撸底层驱动和排查硬件问题。相关博客:【LDC1314】金属传感器(电感传感器)的调试技巧首先,是引脚位的定义与说明:引脚 引脚类型…

    2022年6月8日
    39
  • JSON在PHP中的基本应用

    JSON在PHP中的基本应用从5.2版本开始,PHP原生提供json_encode()和json_decode()函数,前者用于编码,后者用于解码。一、json_encode()该函数主要用来将数组和对象,转换为json格式

    2022年7月4日
    24
  • DeepLab系列学习

    DeepLab系列文章目录DeepLab系列DeepLabV1简介atrousalgorithm利用全卷积增加感受野并加速运算条件随机场CRF实验结果多尺度预测VOC数据集上对比DeepLabV2主要改进简介模型主体ASPP实验结果DeepLabV3相应的改进实验DeepLabV3+(DeepLabV3plus)相应改进整体结构解码器结构modifiedXception实验参考DeepLabV1DeepLabV1github简介DeepLab系列在2015年的ICLR上被提出,主要是使用D

    2022年4月15日
    103
  • 深度学习之卷积神经网络(Convolutional Neural Networks, CNN)

    深度学习之卷积神经网络(Convolutional Neural Networks, CNN)前面,我们介绍了DNN及其参数求解的方法(BP算法),我们知道了DNN仍然存在很多的问题,其中最主要的就是BP求解可能造成的梯度消失和梯度爆炸的问题.那么,人们又是怎么解决这个问题的呢?本节的卷积神经网络(ConvolutionalNeuralNetworks,CNN)就是一种解决方法.我们知道神经网络主要有三个部分组成,分别为:网络结构—描述神经元的层次与连接神经元的结构. 激活函数(激励函数)—用于加入非线性的因素,解决线性模型所不能解决的问题. 参数学习方…

    2025年9月1日
    5
  • 使用电脑模拟微信内置浏览器

    使用电脑模拟微信内置浏览器

    2021年10月23日
    42

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号