springboot + mybatis 的項目,實現簡單的CRUD


以前都是用Springboot+jdbcTemplate實現CRUD

但是趨勢是用mybatis,今天稍微修改,創建springboot + mybatis 的項目,實現簡單的CRUD 

 

 上圖是項目的目錄結構,創建一個user實體,包含id,姓名,手機,密碼,flag等信息,然后對用戶進行增刪查改。

drop table if exists user;

CREATE TABLE `user` (
  id tinyint(4) NOT NULL AUTO_INCREMENT,
  name varchar(200) NOT NULL,
  age int(11) NOT NULL,、
  phone varchar(20) NOT NULL,
  password varchar(20) NOT NULL,
  flag int(4),
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

 

用Intellij IDEA進行開發,創建一個新的springboot項目,選中SQL中的mybaits,生成之后默認帶有DemoApplication主函數啟動類,最后啟動的時候要在主函數上添加mapper掃描@MapperScan("com.example.demo.mapper") //掃描全部mapper

其他的代碼依次如下: User 

public class User implements Serializable {
	private Long id;
	private String name;
	private int age;
	private String phone;
	private String password;
	private boolean flag;

    省略了getter and setter
}

 

userService
package com.example.demo.service;

import com.example.demo.pojo.User;

import java.util.List;

public interface userService {

	List<User> findAll();

	List<User> selectAll();

	List<User> selectById(int id);

	int create(User user);

	int updateUserById(User user);

	int deleteUserById(int id);
}

  

userServiceImp
package com.example.demo.serviceImp;

import com.example.demo.mapper.userMapper;
import com.example.demo.pojo.User;
import com.example.demo.service.userService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class userServiceImp implements userService {

	@Autowired
	private userMapper userMapper;

	public List<User> findAll() {
		System.err.println("查詢所有用戶接口");
		List<User> list = userMapper.findAll();
		return list;
		
	}

	@Override
	public List<User> selectAll() {
		List<User> list = userMapper.selectAll();
		return list;
	}

	@Override
	public List<User> selectById(int id) {
		List<User> list = userMapper.selectById(id);
		return list;
	}


	@Override
	public int create(User user) {
		int count = userMapper.create(user);
		return count;
	}

	@Override
	public int updateUserById(User user) {
		int count = userMapper.updateUserById(user);
		return count;
	}

	@Override
	public int deleteUserById(int id) {
		int count = userMapper.deleteUserById(id);
		return count;
	}

}

  userMapper

package com.example.demo.mapper;

import com.example.demo.pojo.User;

import java.util.List;


public interface userMapper {

	List<User> findAll();

	List<User> selectAll();

	List<User> selectById(int id);

	int create(User user);

	int updateUserById(User user);

	int deleteUserById(int id);
}

  

userController
package com.example.demo.controller;

import com.example.demo.pojo.User;
import com.example.demo.serviceImp.userServiceImp;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Api(tags = {"demo接口"})
@Controller
@RequestMapping("user")
public class userController {

	@Autowired
	private userServiceImp userService;

    @ApiOperation(value = "顯示全部用戶的信息倒序")
    @RequestMapping("userLists")
	@ResponseBody
	public List<User> showUsers() {
		List<User> list = userService.findAll();
		return list;
	}

    @ApiOperation(value = "顯示全部用戶的信息")
	@RequestMapping("selectAll")
	@ResponseBody
	public List<User> selectAll() {
		List<User> list = userService.selectAll();
		return list;
	}

    @ApiOperation(value = "根據ID查詢用戶的信息")
	@RequestMapping("selectById")
	@ResponseBody
	public List<User> selectById(int id) {
		List<User> list = userService.selectById(300);
		return list;
	}

    @ApiOperation(value = "創建新用戶信息")
	@PostMapping("create")
	@ResponseBody
	public String create(User user) {
		int count = userService.create(user);
		System.out.println(count);
		if (count>0)
		return ("成功添加"+count+"條記錄");
		else
			return "添加用戶失敗";
	}

    @ApiOperation(value = "根據ID更新用戶信息")
    @PostMapping("updateUserById")
    @ResponseBody
    public String updateUserById(User user) {
        int count = userService.updateUserById(user);
        System.out.println(count);
        if (count>0)
            return ("成功更新"+count+"條記錄");
        else
            return "更新用戶失敗";
    }

    @ApiOperation(value = "根據ID刪除用戶信息")
    @PostMapping("deleteUserById")
    @ResponseBody
    public String deleteUserById(int id) {
        int count = userService.deleteUserById(id);
        System.out.println(count);
        if (count>0)
            return ("成功刪除"+count+"條記錄");
        else
            return "刪除用戶失敗";
    }



}

  userMapper.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.example.demo.mapper.userMapper">

    <resultMap id="userResultMap" type="com.example.demo.pojo.User">
        <id column="id" property="id" jdbcType="BIGINT"/>
        <result column="name" property="name" jdbcType="VARCHAR"/>
        <result column="age" property="age" jdbcType="VARCHAR"/>
        <result column="phone" property="phone" jdbcType="VARCHAR"/>
        <result column="password" property="password" jdbcType="VARCHAR"/>
        <result column="flag" property="flag" jdbcType="BIGINT"/>
    </resultMap>
    
	
	<select id="findAll" resultMap="userResultMap">
     SELECT id,name,age,phone,password,flag FROM user order by id desc
	</select>

    <select id="selectById" parameterType ="int" resultMap="userResultMap">
        select * from user where id = #{id}
    </select>

    <select id="selectAll" resultMap="userResultMap">
        select * from user order by id desc
    </select>

    <insert id="create" parameterType="com.example.demo.pojo.User">
     insert into user(name,age,phone,password,flag)  values (#{name},#{age},#{phone},#{password},#{flag})
	</insert>

    <update  id="updateUserById" parameterType="com.example.demo.pojo.User">
        update user set name = #{name},age =#{age},phone =#{phone},password = #{password},flag = #{flag} where id = #{id}
    </update>

    <delete  id="deleteUserById" parameterType ="int">
        delete from user where id = #{id}
    </delete>
	

  
</mapper>

 

 

1. Mapper method 'com.example.demo.mapper.userMapper.create attempted to return null from a method with a primitive return type (int).] with root cause

是新增用戶信息接口,發現用戶信息已經成功插入數據庫,但是頁面提示

There was an unexpected error (type=Internal Server Error, status=500).
Mapper method 'com.example.demo.mapper.userMapper.create attempted to return null from a method with a primitive return type (int).
 

出錯原因很簡單,mapper.xml 映射文件中,新增記錄應該用insert,我懶,直接復制了上面的select, 然后搓了很久。。

 

2. 找不到Bean

出錯原因很簡單,啟動類主函數沒有添加mapper掃描,需要添加@MapperScan("com.example.demo.mapper") 

 

 這個項目的github地址是https://github.com/JasmineQian/SpringDemo_2019/tree/master/springboot2mybatis

以前我管理github很亂,自己看到的代碼,自己擼的代碼,都隨便網上塞,然后之后都不怎么回顧。然后就學過什么都忘記了。隱約記得遇到過,具體解決方法不知道。

就像《少林英雄》歌中常的那樣,

練功必須頂大太陽 (哼)
晚上還要借月亮光(哈)
一日不練十日空(哼哈)

 

一日不擼十日空~~~擼代碼,要像練功一樣每日堅持!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM