SpringBoot(三):springboot整合mybatis(xml形式)

来源:互联网 发布:淘宝的国行jbl靠谱吗 编辑:程序博客网 时间:2024/06/06 03:01

springboot访问mysql可以有好几种方式,例如JPA,jdbcTemplate,mybatis等.

但是用习惯了mybatis,个人还是觉得mybatis写xml比较好管理sql语句,多表查询也比较方便.

所以这里只写springboot+mybatis+xml的方式访问mysql


一.初始化mysql表:

DROP TABLE `user` IF EXISTSCREATE TABLE `user` (  `id` varchar(32) NOT NULL,  `name` varchar(255) DEFAULT NULL,  `age` int(11) DEFAULT NULL,  PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;

二.创建项目

选中依赖.



三.配置数据源

spring.datasource.url=jdbc:mysql://192.168.31.125:3306/mj?characterEncoding=utf8&useSSL=true&serverTimezone=UTCspring.datasource.username=rootspring.datasource.password=rootspring.datasource.driver-class-name=com.mysql.jdbc.Driver

四.创建实体类

public class User implements Serializable{private static final long serialVersionUID = -2248190721476487645L;private String id;private String name;private Integer age;get/set 略...}

五.mapper(dao),如果不用xml就直接在这里写sql语句

@Mapper    //标注mybatis的mapper接口public interface UserMapper {void add(User user);void update(User user);void delete(String id);User get(String id);}

六.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.mapper.UserMapper"><insert id="add" parameterType="com.example.entity.User">insert into user (id,name,age) values (#{id},#{name},#{age})</insert><update id="update" parameterType="com.example.entity.User">update user set <if test="name != null and name != ''"> name = #{name}</if><if test="age != null "> age = #{age}</if></update><delete id="delete" parameterType="string"> delete from user where id=#{id}</delete><select id="get" parameterType="string" resultType="com.example.entity.User">select id,name,age from user where id=#{id}</select></mapper>


service层和controller层和springmvc一样,直接略过


七.添加mybatis映射配置

#mybatismybatis.mapper-locations: classpath:mybatis/mapper/*.xml


八.启动项目测试.
postman客户端下载地址:http://pan.baidu.com/s/1boFYR2R密码:ln1f