spring boot 与mybatis整合(xml与注解)

本文介绍了如何在Spring Boot 1.5.20项目中整合MyBatis,详细讲解了从版本选择、目录结构、配置文件、实体类、DAO接口及注解、XML文件到Service和Controller的实现过程。强调了@Mapper和@Param注解的重要性,以及XML映射文件的位置和结构。
摘要由CSDN通过智能技术生成

目录

 

零、版本

一、目录树与所需jar包

二、配置文件

三、实体类

四、dao接口与注解

五、dao接口与xml文件

六、service

七、controller


零、版本

使用java1.8   mysql5.7   spring boot 1.5.20

一、目录树与所需jar包

创建spring boot时,选择

web,mybatis,jdbc,mysql

二、配置文件

可以在application.properties内

#mysql
pring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

mybatis.mapper-locations=classpath:mybatis/*.xml

也可以在application.yml内

spring:  
  datasource:
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&autoReconnect=true&useSSL=false
    username: root
    password: 123456
    driver-class-name: com.mysql.jdbc.Driver
mybatis:  
  mapper-locations: classpath:mapper/*.xml

三、实体类

仅仅与mybatis整合,po类可以不要序列化,但如果和redis二级缓存整合,一定要

package com.xusy.po;

import java.io.Serializable;

public class User  implements Serializable {

	private static final long serialVersionUID = 1435515995276255188L;
    private int id;
    private String name;
    private int 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 int getAge()
	{
		return age;
	}
	public void setAge(int age)
	{
		this.age = age;
	}
	@Override
	public String toString()
	{
		return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
	}

   
    
}

四、dao接口与注解

注意@mapper注解在类UserMapper上

@Param注解的作用是给参数命名,参数命名后就能根据名字得到参数值,正确的将参数传入sql语句中 

简单的sql语句可以在方法上加上@xxx("sql")

注意:xxx分别为Insert,Select,Update,Delete

sql语句被双引号引起,sql语句就是xml文件里被<select>sql</select>中的sql部分

比如

@Select("select s_id id,s_name name,class_id classid from student where  s_name= #{aaaa} and class_id = #{bbbb}") 
    public Student select(@Param("aaaa") String name,@Param("bbbb")int class_id);  
package com.xusy.dao;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import com.xusy.po.User;



@Mapper
public interface UserMapper {

    @Insert("insert into user(name,age) values(#{name},#{age})")
    int addUser(@Param("name")String name,@Param("age")int age);
    
    @Select("select * from user where id =#{id}")
    User findById(@Param("id") int id);
    
    @Update("update user set name=#{name} where id=#{id}")
    void updataById(@Param("id")int id,@Param("name")String name);
    
    @Delete("delete from user where id=#{id}")
    void deleteById(@Param("id")int id);
    
}

五、dao接口与xml文件

package com.xusy.dao;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import com.xusy.po.User;



@Mapper
public interface UserMapper {

    int addUser(@Param("name")String name,@Param("age")int age);
    
    User findById(@Param("id") int id);
    
    void updataById(@Param("id")int id,@Param("name")String name);
    
    void deleteById(@Param("id")int id);
    
}

 这个xml文件可能与接口不对应,参考下即可

注意:这个mapper在resource下的文件加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.xusy.dao.UserMapper">
	
    <resultMap type="com.xusy.po.User" id="userMap">
        <id column="id" property="id" />
        <result column="user_name" property="userName" />
        <result column="pass_word" property="passWord" />
        <result column="create_time" property="createTime" />
    </resultMap>

    <select id="findById" resultType="com.xusy.po.User"
        resultMap="userMap">
        select * from user where id=#{id}
    </select>

    <select id="update" parameterType="com.xusy.po.User">
        update users set
        user_name=#{userName},pass_word=#{passWord},create_time=#{createTime}
        where
        id=#{id}
    </select>
    
    <select id="del" parameterType="java.lang.Integer">
        delete from users where id=#{id}
    </select>
    
    <select id="save" parameterType="com.shyroke.bean.UserBean">
        insert into users(user_name,pass_word,create_time) values(#{userName},#{passWord},#{createTime})
    </select>

</mapper>

六、service

没必要写service的接口,一个类就可以了

package com.xusy.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xusy.dao.UserMapper;
import com.xusy.po.User;



@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;
    
    
    public User findById(int id){
        return userMapper.findById(id);
    }
    
    public int addUser(String name,int age){
        return userMapper.addUser(name,age);
    }
    
    public void updataById(int id,String name){
         userMapper.updataById(id,name);
    }
    
    public void deleteById(int id){
        userMapper.deleteById(id);
    }
}

七、controller

package com.xusy.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.xusy.po.User;
import com.xusy.service.UserService;


@RestController
public class UserController {
    
    @Autowired
    private UserService userService;
    
    @RequestMapping("/adduser")
    @ResponseBody
    public int addUser(@RequestParam("name")String name,@RequestParam("age")int age){
        return userService.addUser(name, age);
    }
    @RequestMapping("/findUser")
    @ResponseBody
    public User findUser(@RequestParam("id") int id){
        return userService.findById(id);
    }
    @RequestMapping("/updataById")
    @ResponseBody
    public String updataById(@RequestParam("id") int id,@RequestParam("name") String name){
        try {
            userService.updataById(id, name);
        } catch (Exception e) {
            return "error";
        }
        return "success";
    }
    
    @RequestMapping("/deleteById")
    @ResponseBody
    public String deleteById(@RequestParam("id") int id){
        try {
            userService.deleteById(id);
        } catch (Exception e) {
            return "error";
        }
        return "success";
    }
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值