springboot 使用mybatis查询的示例代码
示例1
项目结构
代码controller中 UserController.java
package com.example.demo1110.controller;
import com.example.demo1110.entity.User;
import com.example.demo1110.service.UserService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/user")
@CrossOrigin //解决跨域名获取
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/all")
public List<User> getListUser(){
return userService.listUser();
}
@GetMapping("/getId/id={id}")
private User getId(@PathVariable("id") Integer id){
return userService.queryById(id);
}
@PostMapping("/EditUser")
private Map<String,Object> editUser(@RequestBody User user){
System.out.println(user);
HashMap<String,Object> map = new HashMap<>();
try {
userService.editUser(user);
map.put("success",true);
map.put("msg","修改员工成功");
}catch (Exception e){
e.printStackTrace();
map.put("success",false);
map.put("msg","修改员工失败");
}
return map;
}
@GetMapping("/getName")
public List<User> getName(@Param("name") String name){
return userService.queryByName(name);
}
@PostMapping("/addUser")
public Map<String,Object> addUser(@RequestBody User user){
HashMap<String,Object> map = new HashMap<>();
try {
userService.addUser(user);
map.put("success",true);
map.put("msg","添加员工成功");
}catch (Exception e){
e.printStackTrace();
map.put("success",false);
map.put("msg","添加用户失败");
}
return map;
}
@GetMapping("/deletUser/{id}")
public Map<String,Object> deletUser(@PathVariable("id") Integer id){
System.out.println(id);
HashMap<String,Object> map = new HashMap<>();
try {
userService.deleteUserById(id);
map.put("success",true);
map.put("msg","删除员工成功");
}catch (Exception e){
e.printStackTrace();
map.put("success",false);
map.put("msg","删除用户失败");
}
return map;
}
}
entity中 User.java
package com.example.demo1110.entity;
import lombok.Data;
@Data
public class User {
private int id;
private String name;
private int age;
private String city;
}
mapper中 UserDao.java
package com.example.demo1110.mapper;
import com.example.demo1110.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;
@Mapper
@Repository
public interface UserDao {
//查询所有记录
public List<User> listUser();
//按id查询
public User queryById(Integer id);
//按姓名模糊查询
public List<User> queryByName(String name);
//保存用户
public int addUser(User user);
//根据员工id删除
public int deleteUserById(Integer id);
//修改员工信息
public int editUser(User user);
}
service中 UserService.java
package com.example.demo1110.service;
import com.example.demo1110.entity.User;
import java.util.List;
public interface UserService {
//查询所有记录
public List<User> listUser();
//按id查询
public User queryById(Integer id);
//按姓名模糊查询
public List<User> queryByName(String name);
//保存用户
public boolean addUser(User user);
//根据员工id删除
public boolean deleteUserById(Integer id);
//修改员工信息
public boolean editUser(User user);
}
service impl中 UserServiceImpl.java
package com.example.demo1110.service.impl;
import com.example.demo1110.entity.User;
import com.example.demo1110.mapper.UserDao;
import com.example.demo1110.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public List<User> listUser() {
return userDao.listUser();
}
@Override
public User queryById(Integer id) {
return userDao.queryById(id);
}
@Override
public List<User> queryByName(String name) {
return userDao.queryByName(name);
}
@Override
public boolean addUser(User user) {
int i = userDao.addUser(user);
if(i > 0){
return true;
}else {
return false;
}
}
@Override
public boolean deleteUserById(Integer id) {
int i = userDao.deleteUserById(id);
if(i > 0){
return true;
}else {
return false;
}
}
@Override
public boolean editUser(User user) {
int i = userDao.editUser(user);
if(i > 0){
return true;
}else {
return false;
}
}
}
主java文件 Demo1110Application.java
package com.example.demo1110;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@MapperScan("com.example.demo1110.mapper")
@SpringBootApplication
public class Demo1110Application {
public static void main(String[] args) {
SpringApplication.run(Demo1110Application.class, args);
}
}
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.demo1110.mapper.UserDao">
<select id="listUser" resultType="com.example.demo1110.entity.User">
select * from user
</select>
<select id="queryById" parameterType="int" resultType="com.example.demo1110.entity.User">
select * from user
where id = #{id}
</select>
<select id="queryByName" parameterType="String" resultType="com.example.demo1110.entity.User">
select * from user
where username = #{name}
</select>
<insert id="addUser" parameterType="com.example.demo1110.entity.User">
insert into user values (#{id},#{username},#{age},#{city})
</insert>
<delete id="deleteEmployeeById" parameterType="int">
delete from user where id = #{id}
</delete>
<update id="editEmployee" parameterType="com.example.demo1110.entity.User">
update user
set username = #{name},age = #{age},city = #{city}
where id = #{id}
</update>
</mapper>
application.yml
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/mybatisdemo?characterEncoding=utf-8&useSSL=false
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
mapper-locations: classpath*:mapper/查询所有记录
public List<User> listUser();
//按id查询
public User queryById(Integer id);
//按姓名模糊查询
public List<User> queryByName(String name);
//保存用户
public int addUser(User user);
//根据员工id删除
public int deleteUserById(Integer id);
//修改员工信息
public int editUser(User user);*/
List<User> findAllUser();
User findUser(Integer id);
void insertUser(User user);
void deleteUser(Integer id);
void updateUser(User user);
void deleteUserByList(Integer[] ids);
}
service -> UserService.java
package com.example.demo1110.service;
import com.example.demo1110.entity.User;
import java.util.List;
public interface UserService {
List<User> findAll();
User findUserById(Integer id);
void insertUser(User user);
void updateUser(User user);
void deleteUser(Integer id);
void deleteUserByList(Integer[] ids);
}
service impl ->UserServiceImpl.java
package com.example.demo1110.service.impl;
import com.example.demo1110.entity.User;
import com.example.demo1110.mapper.UserMapper;
import com.example.demo1110.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User findUserById(Integer id) {
return userMapper.findUser(id);
}
@Override
public List<User> findAll() {
return userMapper.findAllUser();
}
@Override
public void insertUser(User user) {
userMapper.insertUser(user);
}
@Override
public void updateUser(User user) {
userMapper.updateUser(user);
}
@Override
public void deleteUser(Integer id) {
userMapper.deleteUser(id);
}
@Override
public void deleteUserByList(Integer[] ids) {
userMapper.deleteUserByList(ids);
}
}
controller ->UserController.java
package com.example.demo1110.controller;
import com.example.demo1110.entity.User;
import com.example.demo1110.service.UserService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/user")
@CrossOrigin //解决跨域名获取
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/{id}")
public User findUserByid(@PathVariable("id") Integer id){
return userService.findUserById(id);
}
@GetMapping("/findAll")
public List<User> findAll(){
return userService.findAll();
}
@PostMapping("/add")
// // post转实体对象 只能用raw application/json格式传参 key-value跟实体对应 controller用@RequestBody
public void insertUser(@RequestBody User user){
userService.insertUser(user);
}
@PutMapping("/update")
public void updateUser(@RequestBody User user){
userService.updateUser(user);
}
@DeleteMapping("/delete/{id}")
public void deleteUser(@PathVariable("id") Integer id){
userService.deleteUser(id);
}
@DeleteMapping("/deleteBatch")
public void deleteBatch(@RequestBody Integer[] ids){
userService.deleteUserByList(ids);
}
}
controller ->IndexController.java
package com.example.demo1110.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class IndexController {
@RequestMapping ("/")
String home () {
return "hello world!!";
}
}
resources mapper -> 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.demo1110.mapper.UserMapper">
<select id="listUser" resultType="com.example.demo1110.entity.User">
select * from user
</select>
<select id="queryById" parameterType="int" resultType="com.example.demo1110.entity.User">
select * from user
where id = #{id}
</select>
<select id="queryByName" parameterType="String" resultType="com.example.demo1110.entity.User">
select * from user
where username = #{name}
</select>
<insert id="addUser" parameterType="com.example.demo1110.entity.User">
insert into user values (#{id},#{username},#{age},#{city})
</insert>
<delete id="deleteEmployeeById" parameterType="int">
delete from user where id = #{id}
</delete>
<update id="editEmployee" parameterType="com.example.demo1110.entity.User">
update user
set username = #{name},age = #{age},city = #{city}
where id = #{id}
</update>
</mapper>-->
<mapper namespace="com.example.demo1110.mapper.UserMapper">
<resultMap id="user" type="com.example.demo1110.entity.User">
<id column="id" property="id"/>
<result column="age" property="age"/>
<result column="name" property="name"/>
</resultMap>
<select id="findUser" parameterType="int" resultMap="user">
select * from user
<where>
<if test="_parameter!=null">
and id = #{id}
</if>
</where>
</select>
<select id="findAllUser" resultMap="user">
select * from user
</select>
<sql id="key">
<trim suffixOverrides=",">
<if test="id!=null">
id,</if>
<if test="name!=null">
name,
</if>
<if test="age!=null">
age,
</if>
</trim>
</sql>
<sql id="value">
<trim suffixOverrides=",">
<if test="id!=null">
#{id},
</if>
<if test="name!=null">
#{name},
</if>
<if test="age!=null">
#{age},
</if>
</trim>
</sql>
<insert id="insertUser" parameterType="user">
insert into user(<include refid="key"/>) values (<include refid="value"/>)
</insert>
<update id="updateUser" parameterType="user">
UPDATE user
<trim prefix="set" suffixOverrides=",">
<if test="age!=null">age=#{age},</if>
<if test="name!=null and name !=''">name=#{name},</if>
</trim>
WHERE id=#{id}
</update>
<delete id="deleteUser" parameterType="Integer">
delete from user where id = #{id}
</delete>
<delete id="deleteUserByList">
delete from user where id in
<foreach collection="array" open="(" close=")" separator="," item="id">
#{id}
</foreach>
</delete>
</mapper>
测试运行项目
http://127.0.0.1:8080/user/findAll
返回数据
[{"id":1,"name":"小明","age":18,"city":"深圳"},{"id":2,"name":"小明1","age":18,"city":"深圳"}]
源代码
链接: https://pan.baidu.com/s/11CVG6FyWrm67HR_ONVnVYw
提取码: tdfr
到此这篇关于springboot 使用mybatis查询的文章就介绍到这了,更多相关springboot mybatis查询内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341