springboot03、实现mybatis

2022-11-30 17:18:01 浏览数 (1)

springboot03、实现mybatis

目录

1、pom引包

2、数据源配置application.properties

3、model对应数据库的类Users

4、dao层·需要加上@Repository注解

5、添加映射文件UsersMapper.xml

6、service层编码

7、serviceimpl层编码

8、Controller层编码

9、测试效果:


1、pom引包

代码语言:javascript复制
	   <dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>
		<!-- 热部署 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
		</dependency>
		<!-- Web支持 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<!-- JDBC -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
		</dependency>
		<!-- MySQL驱动 -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>
		<!-- 集成MyBatis -->
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>2.1.2</version>
		</dependency>
		<!-- junit -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<scope>test</scope>
		</dependency>
		<!-- 测试 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>

2、数据源配置application.properties

Spring Boot 会将数据源自动注入到 MyBatis 的 sqlSessionFactory 组件中。对于我们开发者来说,这一切都是自动实现的,非常简单。

代码语言:javascript复制
# 配置数据库驱动
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# 配置数据库url
spring.datasource.url=jdbc:mysql://rm-bp1zq3879r28p726lco.mysql.rds.aliyuncs.com:3306/test?characterEncoding=utf8
# 配置数据库用户名
spring.datasource.username=qwe8403000
# 配置数据库密码
spring.datasource.password=Qwe8403000
# 指定MyBatis配置文件位置
mybatis.mapper-locations=classpath:mapper/*.xml
# 指定模型位置
mybatis.typeAliasesPackage=com.item.model
# 修改端口号避免冲突
server.port=8088
# 服务路径
server.servlet.context-path=/demospring

3、model对应数据库的类Users

代码语言:javascript复制
package com.item.model;
 
public class Users {
 
    public int getId() {
        return id;
    }
 
    public void setId(int id) {
        this.id = id;
    }
 
    public String getUserName() {
        return userName;
    }
 
    public void setUserName(String userName) {
        this.userName = userName;
    }
 
    public String getPwd() {
        return pwd;
    }
 
    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
 
    public String getNickName() {
        return nickName;
    }
 
    public void setNickName(String nickName) {
        this.nickName = nickName;
    }
 
    @Override
    public String toString() {
        return "Users{"  
                "id="   id  
                ", userName='"   userName   '''  
                ", pwd='"   pwd   '''  
                ", nickName='"   nickName   '''  
                '}';
    }
 
    private int id;
    private String userName;
    private String pwd;
    private String nickName;
 
}

4、dao层·需要加上@Repository注解

代码语言:javascript复制
package com.item.dao;

import com.item.model.Users;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
/**
 * 数据访问组件
 */
@Repository
public interface UsersMapper {
    List<Users> GetInfo();
    List<Users> SelectName(@Param("nickName") String nickName);
    Users UsersSelectById(@Param("id") int id);
    int UsersAddInfo(
            @Param("userName") String userName,
            @Param("pwd") String pwd,
            @Param("nickName") String nickName
    );
    int UsersUpdateInfo(
            @Param("pwd") String pwd,
            @Param("id") int id
    );
    int UsersDeleteById(@Param("id") int id);
}

5、添加映射文件UsersMapper.xml

代码语言:javascript复制
<?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.item.dao.UsersMapper">
    <!-- 用作基础查询测试 -->
    <select id="GetInfo" resultType="Users">
        select * from users
    </select>
    <!-- 用做传递参数测试 -->
    <select id="SelectName" resultType="Users">
        select * from users where nickName like "%${nickName}%"
    </select>
    <!-- id精准查询 -->
    <select id="UsersSelectById" resultType="Users">
        select * from users where id=#{id}
    </select>
    <!-- 增加 -->
    <insert id="UsersAddInfo">
        insert into users values(0,"${userName}","${pwd}","${nickName}");
    </insert>
    <!-- 修改 -->
    <update id="UsersUpdateInfo">
        update users set pwd="${pwd}" where id=#{id}
    </update>
    <!-- 删除 -->
    <delete id="UsersDeleteById">
        delete from users where id=#{id}
    </delete>
</mapper>

6、service层编码

代码语言:javascript复制
package com.item.service;
 
import com.item.model.Users;

import java.util.List;
 
public interface UsersService {
    /**
     * 获取所有
     * @return
     */
    List<Users> GetInfo();
 
    /**
     * 获取nickName的模糊查询结果集
     * @param nickName
     * @return
     */
    List<Users> SelectName(String nickName);
 
    /**
     * id精准查询
     * @param id
     * @return
     */
    Users UsersSelectById(int id);
 
    /**
     * 添加信息
     * @param userName
     * @param pwd
     * @param nickName
     * @return
     */
    int UsersAddInfo(
            String userName,
            String pwd,
            String nickName
    );
 
    /**
     * 修改密码
     * @param pwd
     * @param id
     * @return
     */
    int UsersUpdateInfo(
            String pwd,
            int id
    );
 
    /**
     * 删除信息
     * @param id
     * @return
     */
    int UsersDeleteById(int id);
}

7、serviceimpl层编码

代码语言:javascript复制
package com.item.serviceimpl;
 
import com.item.dao.UsersMapper;
import com.item.model.Users;
import com.item.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
 
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
 
@Service
public class UsersServiceImpl implements UsersService {
    @Autowired
    private UsersMapper usersMapper;
 
    @Override
    public List<Users> GetInfo() {
        return usersMapper.GetInfo();
    }
 
    @Override
    public List<Users> SelectName(String nickName) {
        return usersMapper.SelectName(nickName);
    }
 
    @Override
    public Users UsersSelectById(int id) {
        return usersMapper.UsersSelectById(id);
    }
 
    @Override
    public int UsersAddInfo(String userName, String pwd, String nickName) {
        pwd=encrypt(pwd);
        return usersMapper.UsersAddInfo(userName, pwd, nickName);
    }
 
    @Override
    public int UsersUpdateInfo(String pwd, int id) {
        pwd=encrypt(pwd);
        return usersMapper.UsersUpdateInfo(pwd, id);
    }
 
    /**
     * MD5加密
     * @param password
     * @return
     */
    private String encrypt(String password) {
        String passwordMd5 = null;
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(password.getBytes("utf-8"));
            passwordMd5 = toHex(bytes);
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return passwordMd5;
    }
 
    private static String toHex(byte[] bytes) {
        final char[] HEX_DIGITS = "0123456789ABCDEF".toCharArray();
        StringBuilder ret = new StringBuilder(bytes.length * 2);
        for (int i = 0; i < bytes.length; i  ) {
            ret.append(HEX_DIGITS[(bytes[i] >> 4) & 0x0f]);
            ret.append(HEX_DIGITS[bytes[i] & 0x0f]);
        }
        return ret.toString();
    }
 
    @Override
    public int UsersDeleteById(int id) {
        return usersMapper.UsersDeleteById(id);
    }
}

8、Controller层编码

代码语言:javascript复制
package com.item.controller;

import com.item.model.Users;
import com.item.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;

@RestController
@CrossOrigin
public class UsersController {
    @Autowired
    private UsersService usersService;

    @GetMapping("/GetInfoApi")
    public Object GetInfoApi(){
        List<Users> list=usersService.GetInfo();
        HashMap<String,Object> map=new HashMap<String,Object>();
        map.put("state",true);
        map.put("msg","成功");
        map.put("result",list);
        return map;
    }

    @GetMapping("/GetName")
    public Object GetName(HttpServletRequest request,Model model){
        String nickName = request.getParameter("nickName");
        List<Users> list=usersService.SelectName(nickName);
        HashMap<String,Object> map=new HashMap<String,Object>();
        map.put("state",true);
        map.put("msg","成功");
        map.put("result",list);
        return map;
    }

    /**
     * 添加接口,访问方式post
     * @param request
     * @param model
     * @return
     */
    @PostMapping(value = "/UserAddInfoApi")
    public Object UserAddInfoApi(HttpServletRequest request,Model model){
        String userName = request.getParameter("userName");
        String pwd = request.getParameter("pwd");
        String nickName = request.getParameter("nickName");
        usersService.UsersAddInfo(userName, pwd, nickName);
        HashMap<String,Object> map=new HashMap<String,Object>();
        map.put("state",true);
        map.put("msg","成功");
        map.put("result","");
        return map;
    }

    /**
     * 单个查询
     * @param request
     * @param model
     * @return
     */
    @GetMapping("/UsersSelectById")
    public Object UsersSelectById(HttpServletRequest request,Model model){
        String id = request.getParameter("id");
        Users users = usersService.UsersSelectById(Integer.parseInt(id));
        HashMap<String,Object> map=new HashMap<String,Object>();
        map.put("state",true);
        map.put("msg","成功");
        map.put("result",users);
        return map;
    }

    /**
     * 修改api
     * @param request
     * @param model
     * @return
     */
    @PostMapping(value = "/UserUpdateInfoApi")
    public Object UserUpdateInfoApi(HttpServletRequest request,Model model){
        String id = request.getParameter("id");
        String pwd = request.getParameter("pwd");
        usersService.UsersUpdateInfo(pwd,Integer.parseInt(id));
        HashMap<String,Object> map=new HashMap<String,Object>();
        map.put("state",true);
        map.put("msg","成功");
        map.put("result","");
        return map;
    }

    /**
     * 删除api
     * @param request
     * @param model
     * @return
     */
    @GetMapping(value = "/UsersDeleteById")
    public Object UsersDeleteById(HttpServletRequest request,Model model){
        String id = request.getParameter("id");
        usersService.UsersDeleteById(Integer.parseInt(id));
        HashMap<String,Object> map=new HashMap<String,Object>();
        map.put("state",true);
        map.put("msg","成功");
        map.put("result","");
        return map;
    }
}

备注:dao层引入

代码语言:javascript复制
package com.item;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
@MapperScan("com.item.dao")
@SpringBootApplication
public class Action extends SpringBootServletInitializer {
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Action.class);
    }
    public static void main(String[] args) {
        SpringApplication.run(Action.class,args);//一定是被@SpringBootApplication标记的类
    }
}

9、测试效果:

可以使用postman测试:

效果很明显,成功了。

0 人点赞