先创建application.yml,在内部配置mybatis相关配置文件,然后根据mybatis约定的格式再创建**Mapper.xml。把内部namespace改成com.example.java_gobang.model.UserMapper
1.创建application.yml
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/java_gobang?characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8
username: root
password: 1234
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis: #约定mybatis未来要去哪个路径下去加载配置文件
mapper-locations: classpath:mapper/**Mapper.xml
logging:
pattern:
console: "[%-5level] - %msg%n"
2.创建mapper包,再创建**Mapper.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.java_gobang.model.UserMapper">
<insert id="insert"> <!--这个id内部的名字需要跟model.UserMapper内部的方法名匹配-->
insert into user values(null, #{username}, #{password}, 1000, 0, 0);
</insert>
<select id="selectByName" resultType="com.example.java_gobang.model.User">
select * from user where username = #{username};
</select>
<update id="userWin">
update user set totalCount = totalCount + 1, winCount = winCount + 1, score = score + 30
where userId = #{userId}
</update>
<update id="userLose">
update user set totalCount = totalCount + 1, score = score - 30
where userId = #{userId}
</update>
</mapper>
3.创建model包,再创建UserMapper
package com.example.java_gobang.model;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserMapper {
// 往数据库里插入一个用户. 用于注册功能.
void insert(User user);
// 根据用户名, 来查询用户的详细信息. 用于登录功能
User selectByName(String username);
// 总比赛场数 + 1, 获胜场数 + 1, 天梯分数 + 30
void userWin(int userId);
// 总比赛场数 + 1, 获胜场数 不变, 天梯分数 - 30
void userLose(int userId);
}