Spring Boot学习笔记(五)整合mybatis

时间:2022-12-30 12:54:18

pom文件里添加依赖

    <!-- 数据库需要的依赖 -->        
  
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency> <dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency> <dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.0</version>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

application.properties
我用的是springBoot 2.1 不需要配置驱动,配置驱动的话反而会出现警告
#数据库
spring.datasource.url=jdbc:mysql://192.168.238.130:3306/dev?useUniode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=123


Mapper.java文件
import java.util.ArrayList;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Many;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select; import com.sc.Firstboot.entity.User; public interface MainMapper { /**
* 简单查询的话可以用下面这中注解的方式,比较简洁
* 复杂查询还是需要用到mapper.xml配置文件来完成
* @return
*/ @Select("select * from user")
public ArrayList<User> find(); @Insert("insert into user(id,username,age,pwd) values(#{id},#{username},#{age},#{pwd})")
public int insert(@Param("id") String id, @Param("username") String username, @Param("age") int age,
@Param("pwd") String pwd); public ArrayList<User> findAllAndPro();
}

Mapper.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="com.sc.Firstboot.dao.MainMapper"> <select id="findAllAndPro" resultMap="userMap">
select
us.id,us.username,us.pwd,us.age,pru.id as pid ,
pru.productName,pru.price,pru.total
from user us
left join product pru on pru.uid = us.id
</select> <!-- 注意:当多个表的字段名一样的时候,查询需要用别名,否则查询结果不理想 -->
<resultMap id="userMap" type="com.sc.Firstboot.entity.User">
<id property="id" column="id" />
<result property="userName" column="userName" />
<result property="pwd" column="pwd" />
<result property="age" column="age" />
<collection property="pList" ofType="com.sc.Firstboot.entity.Product">
<id property="id" column="pid" />
<result property="productName" column="productName" />
<result property="total" column="total" />
</collection>
</resultMap> </mapper>
service
@Service
public class MainService { @Autowired
private MainMapper mainMapper; public String insert(User user){
if(1 == mainMapper.insert("ewq", user.getUserName(),user.getAge(), user.getPwd()))return "success";
return "faild";
} public ArrayList<User> findAll(){
return mainMapper.find();
} public ArrayList<User> findAllAndPro(){
return mainMapper.findAllAndPro();
} }

controller

@Controller
public class MainController { @Autowired
private MainService mainSerice; /**
* 传参的时候需要注意区分命名,尽量不要使用相同的命名,
* 否则的框架会给形参列表中所有的实体里所有相同的属性名都赋值
* 例如 User实体和Product实体中都有id属性
* 那么传参的时候如果 id=XXX 那么两个实体的id都会被赋值XXX
* @param user
* @param product
* @return
*/
@ResponseBody
@RequestMapping(path = {"/insertUser"}, method = {RequestMethod.GET, RequestMethod.POST})
public String insertUser(User user,Product product){
System.out.println(user.toString());
System.out.println(product.toString());
return mainSerice.insert(user);
} @ResponseBody
@RequestMapping(path = {"/findAll"}, method = {RequestMethod.GET, RequestMethod.POST})
public ModelAndView findAll(){
ModelAndView mv = new ModelAndView();
Map<String,Object> map = new HashMap<>();
map.put("userList",mainSerice.findAll());
mv.setViewName("login/login");
mv.addObject("result",map);
return mv;
} @ResponseBody
@RequestMapping(path = {"/findAllAndPro"}, method = {RequestMethod.GET, RequestMethod.POST})
public ModelAndView findAllAndPro(){
ModelAndView mv = new ModelAndView();
Map<String,Object> map = new HashMap<>();
map.put("userList",mainSerice.findAllAndPro());
mv.setViewName("login/login");
mv.addObject("result",map);
return mv;
}
}

Application.java

/**
* 启动mapper文件的扫描注解
* 他会去制定的包范围下扫描所有以Mapper接吻的java文件
* 默认扫整个项目
* @author lenovo
*
*/
@SpringBootApplication
@MapperScan(basePackages={"com.sc.myProject.dao"})
public class Application { public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

Spring Boot学习笔记(五)整合mybatis的更多相关文章

  1. Spring Boot 学习笔记&lpar;六&rpar; 整合 RESTful 参数传递

    Spring Boot 学习笔记 源码地址 Spring Boot 学习笔记(一) hello world Spring Boot 学习笔记(二) 整合 log4j2 Spring Boot 学习笔记 ...

  2. Spring Boot 知识笔记(整合Mybatis)

    一.pom.xml中添加相关依赖 <!-- 引入starter--> <dependency> <groupId>org.mybatis.spring.boot&l ...

  3. Spring Boot学习笔记:整合Shiro

    Spring Boot如何和Shiro进行整合: 先自定义一个Realm继承AuthorizingRealm,并实现其中的两个方法,分别对应认证doGetAuthenticationInfo和授权do ...

  4. Spring Boot学习笔记:整合H2数据库

    H2数据库:java语言编写的嵌入式sql数据库.可以和应用一起打包发布. H2有三种连接模式(Connection Modes): Embedded mode (local connections ...

  5. Spring Boot 知识笔记(整合Mybatis续-补充增删改查)

    续上篇,补充数据库增删改查的其他场景. 一.Mapper中添加其他场景操作 package net.Eleven.demo.Mapper; import net.Eleven.demo.domain. ...

  6. Spring Boot学习笔记2——基本使用之最佳实践&lbrack;z&rsqb;

    前言 在上一篇文章Spring Boot 学习笔记1——初体验之3分钟启动你的Web应用已经对Spring Boot的基本体系与基本使用进行了学习,本文主要目的是更加进一步的来说明对于Spring B ...

  7. Spring Boot 2&period;X&lpar;五&rpar;:MyBatis 多数据源配置

    前言 MyBatis 多数据源配置,最近在项目建设中,需要在原有系统上扩展一个新的业务模块,特意将数据库分库,以便减少复杂度.本文直接以简单的代码示例,如何对 MyBatis 多数据源配置. 准备 创 ...

  8. Spring Boot 学习笔记--整合Thymeleaf

    1.新建Spring Boot项目 添加spring-boot-starter-thymeleaf依赖 <dependency> <groupId>org.springfram ...

  9. spring boot整合jsp的那些坑(spring boot 学习笔记之三)

    Spring Boot 整合 Jsp 步骤: 1.新建一个spring boot项目 2.修改pom文件 <dependency>            <groupId>or ...

随机推荐

  1. Google之Chromium浏览器源码学习——base公共通用库&lpar;三&rpar;

    本节将介绍base公共通用库中的containers,其包含堆栈.列表.集合.以及Most Recently Used cache(最近使用缓存模板). linked_list.h:一个简单的列表类型 ...

  2. java设计模式(八) 适配器模式

    [适配器模式]将一个类的接口,转换成客户期望的另外一个接口.适配器让原本接口不兼容的类可以合作无间. 1,Duck接口 package com.pattern.adapter; public inte ...

  3. 【BZOJ 3879】SvT

    http://www.lydsy.com/JudgeOnline/problem.php?id=3879 SvT的中文是后缀虚树? 反正本蒟蒻不懂,还是$O(nlogn)$的后缀数组和单调栈维护来做, ...

  4. meta viewport 详解

    ViewPort <meta>标记用于指定用户是否可以缩放Web页面,如果可以,那么缩放到的最大和最小缩放比例是什么.使用ViewPort <meta>标记还表示文档针对移动设 ...

  5. innodb buffer pool

    add page to flush list buffer pool中的page,有三种状态: l  free:      当前page未被使用 l  clean:    当前page被使用,对应于数 ...

  6. Spring redirect直接返回项目根文件夹

    return "redirect:/";

  7. 判断一个字符串中是否包含另一个字符串(KMP、BF)

    判断一个字符串是否是另一个字符串的子串,也就是strstr()函数的实现,简单的实现方法是BF算法. 1.BF算法 int BF(char *s, char *p){ ; ; int j; while ...

  8. &lbrack;C&num;&rsqb;使用Redis来存储键值对(Key-Value Pair)

    本文为原创文章.源代码为原创代码,如转载/复制,请在网页/代码处明显位置标明原文名称.作者及网址,谢谢! 开发工具:VS2017 语言:C# DotNet版本:.Net FrameWork 4.5及以 ...

  9. MySQL5&period;7&period;20安装过程报错CMake Error at cmake&sol;boost&period;cmake&colon;81 &lpar;MESSAGE&rpar;&colon;

    MySQL在5.7版本及以后,都需要boots 库,所以需要先安装boots 步骤: 1.在/usr/local下创建 名为boots的目录 mkdir -p /usr/local/boots 2.进 ...

  10. centos7忘记密码处理办法

    centos7忘记密码处理办法 此界面按e进入grub编辑界面 进入grub编辑界面.把linux16这行的ro修改为rw init=/sysroot/bin/sh. 按ctrl+x进入单用户模式 登 ...