spring boot集成mybatis时使用xml配置的方式
-
新建User.xml文件
在resource文件夹下新建mapper文件夹,然后新建User.xml.
-
安装mybatisx插件
mybatisx插件,方便xml文件与数据层切换。在.xml文件出现小鸟图标说明建立成功并且.xml与mapper建立了关联。
添加代码如下:
<?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">
<!--namespace指向mapper.xml所对应的Mapper接口-->
<mapper namespace="com.example.demo.demos.web.demo.mapper.UserMapper">
<update id="update">
update sys_user
<set><!--这里我们做这样的判断,主要是为了实现不将原有的数据置空,当然,也可以不判断,就写最基本的SQL语句-->
<if test="username !=null ">
username=#{username},
</if>
<if test="password !=null ">
password=#{password},
</if><!--一般情况password不能修改,修改密码我们通常再做一个单独的业务-->
<if test="nickname !=null ">
nickname=#{nickname},
</if>
<if test="email !=null ">
email=#{email},
</if>
<if test="phone !=null ">
phone=#{phone},
</if>
<if test="address !=null ">
address=#{address}
</if>
</set>
<where>
id=#{id}
</where>
</update>
</mapper>
- 删除Usermapper中的
@update
注解
@update
与.xml配置只能二选一,因此去掉注解。
- 修改yml配置文件
server:
port: 8080
spring:
datasource:
username: root
password: 123456
#url中database为对应的数据库名称,这里为class
url: jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
thymeleaf:
prefix: classpath:/templates/
suffix: .html
cache: false
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
mybatis:
mapper-locations: classpath:mapper/*.xml #扫描所有mapper文件夹
-
测试结果
postman测试结果:
数据库查询结果:
数据改变,成功,如果有不明白请看之前博客。