温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在SpringBoot中使用MyBatis操作数据

发布时间:2021-04-07 16:44:04 来源:亿速云 阅读:206 作者:Leah 栏目:编程语言

怎么在SpringBoot中使用MyBatis操作数据?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

首先我们先创建一个SpringBoot 项目。

怎么在SpringBoot中使用MyBatis操作数据

数据库连接配置

##数据库连接配置(部署到哪台,对应的ip需修改)
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/mybatis?connectTimeout=1000&useSSL=false&useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver=com.mysql.jdbc.Driver

数据库中的数据

怎么在SpringBoot中使用MyBatis操作数据

环境配好之后,下面分别介绍一下通过注解或者通过xml映射的形式这两种方法来使用MyBatis。

通过xml映射的形式

测试Bean

package com.example.demo.model;

public class User {
 private int id;
 private String name;
 private String sex;
 private int age;

 public User() {
 }

 public User(String name, String sex, int age) {
  this.name = name;
  this.sex = sex;
  this.age = age;
 }

 public User(int id, String name, String sex, int age) {
  this.id = id;
  this.name = name;
  this.sex = sex;
  this.age = age;
 }

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getSex() {
  return sex;
 }

 public void setSex(String sex) {
  this.sex = sex;
 }

 public int getAge() {
  return age;
 }

 public void setAge(int age) {
  this.age = age;
 }
}

XML形式的具体操作

将mapper定义为接口,只定义方法。具体的实现在同名的xml文件中。

package com.example.demo.mapper;

import com.example.demo.model.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

@Mapper
public interface UserMapper {
 User getByName(@Param("name") String name);

 boolean insert(User user);

 boolean update(@Param("name") String name, @Param("sex") String sex, @Param("age") int age);

 void delete(@Param("name") String name);
}
<?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.example.demo.mapper.UserMapper">
 <select id="getByName" resultType="com.example.demo.model.User" parameterType="java.lang.String">
  SELECT * FROM tb_user WHERE name = #{name}
 </select>

 <insert id="insert" parameterType="com.example.demo.model.User" useGeneratedKeys="true">
  INSERT INTO tb_user(name, sex, age) VALUES(#{name}, #{sex}, #{age})
 </insert>

 <update id="update" parameterType="com.example.demo.model.User">
  UPDATE tb_user SET sex=#{sex}, age=#{age} WHERE name=#{name}
 </update>

 <delete id="delete" parameterType="java.lang.String">
  DELETE FROM tb_user WHERE name = #{name}
 </delete>
</mapper>

两个文件通过mapper.xml文件中的 namespace 形成映射。

一般情况下,我们用到的资源文件(各种xml,properites,xsd文件等)都放在src/main/resources下面(springboot回到对应的位置加载文件),利用maven打包时,maven能把这些资源文件打包到相应的jar或者war里。但是,有的时候我们习惯把它和Mapper.java放一起,都在src/main/java下面,这样利用maven打包时,就需要修改pom.xml文件,来把mapper.xml文件一起打包进jar或者war里了,否则,这些文件不会被打包的。(maven认为src/main/java只是java的源代码路径)。

所以说,如果要将mapper.java和mapper.xml文件放在同一个位置,就需要在pom文件中指定xml文件的加载位置。

怎么在SpringBoot中使用MyBatis操作数据

 <build>
 <resources> 
  <!-- maven项目中src源代码下的xml等资源文件编译进classes文件夹,
   注意:如果没有这个,它会自动搜索resources下是否有mapper.xml文件,
   如果没有就会报org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): ... -->
  <resource> 
  <directory>src/main/java</directory> 
  <includes> 
   <include>**/*.xml</include> 
  </includes> 
  <filtering>true</filtering>
  </resource>
  
  <!--将resources目录下的配置文件编译进classes文件 --> 
  <resource>
   <directory>src/main/resources</directory>
   <filtering>true</filtering>
  </resource>
 </resources> 
 </build>

如果mapper.java和mapper.xml文件是分开放置的,则不需要以上配置。

怎么在SpringBoot中使用MyBatis操作数据

Service服务

package com.example.demo.service;

import com.example.demo.model.User;

public interface UserService {
 User getUserByName(String name);

 boolean addUser(User user);

 boolean updateUser(String name, String sex, int age);

 void deleteUser(String name);
}

Service服务的实现类

package com.example.demo.service.impl;

import com.example.demo.mapper.UserMapper;
import com.example.demo.model.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService{
 @Autowired
 UserMapper userMapper;

 @Override
 public User getUserByName(String name) {
  User user = userMapper.getByName(name);
  if (null != user){
   return user;
  }
  return null;
 }

 @Override
 public boolean addUser(User user) {
  return userMapper.insert(user);
 }

 @Override
 public boolean updateUser(String name, String sex, int age) {
  return userMapper.update(name, sex, age);
 }

 @Override
 public void deleteUser(String name) {
  userMapper.delete(name);
 }
}

测试接口

package com.example.demo.controller;

import com.example.demo.model.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {
 @Autowired
 UserService userService;

 @RequestMapping(value = "/index", method = RequestMethod.GET)
 public String index(){
  User user = userService.getUserByName("gyl");
  return user.getName()+"--"+user.getSex()+"--"+user.getAge();
 }
}

如果一切顺利,即将输入localhost:8080/index 你将看到如下内容

怎么在SpringBoot中使用MyBatis操作数据

通过注解的方式

package com.example.demo.mapper;

import com.example.demo.model.User;
import org.apache.ibatis.annotations.*;

@Mapper
public interface UserMapper {

 @Select("select * from TB_USER where NAME = #{name}")
 User getByName(@Param("name") String name);

 @Insert("insert into TB_USER(NAME, SEX, AGE) values(#{name}, #{sex}, #{age})")
 boolean insert(User user);

 @Update("update TB_USER set SEX=#{sex}, AGE=#{age} where NAME=#{name}")
 boolean update(@Param("name") String name, @Param("sex") String sex, @Param("age") int age);

 @Delete("delete from TB_USER where NAME = #{name}")
 void delete(@Param("name") String name);
}

如果一切顺利,即将输入localhost:8080/index 你将看到如下内容

怎么在SpringBoot中使用MyBatis操作数据

关于怎么在SpringBoot中使用MyBatis操作数据问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI