1). 创建项目
按图片填写相关内容
2). 填写相关配置
3). 配置工具
Web -> web,SQL -> MySQL 和 MyBatis
4). 配置项目
5). application.properties配置
#tomcat端口
server.port=8080
#数据连接
# 连接地址
spring.datasource.url=jdbc:mysql://localhost:3306/blog?useUnicode=true&characterEncoding=utf8
# 用户名
spring.datasource.username=root
# 密码
spring.datasource.password=root
# 驱动名
spring.datasource.driverClassName=com.mysql.jdbc.Driver
#Mybatis扫描
mybatis.mapper-locations=classpath*:mapper/*.xml
6). 数据库表
7). 创建用户实体类
- User
/**
* 用户实体类
*/
data class User (
val id: Long,
val name: String,
val age: Int
)
8). 创建UserDao
/**
* 要为Dao层接口上面添加一个@Mapper注解。
与springbootApplication中的@MapperScan二选一写上即可
*/
@Mapper
interface UserDao {
fun selectUserByName(name: String): User
}
9). 创建UserMapper.xml
创建位置: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.mazaiting.blog.dao.UserDao">
<select id="selectUserByName" resultType="com.mazaiting.blog.domain.User">
SELECT * FROM user WHERE name = #{name}
</select>
</mapper>
10). 创建UserService
@Service
class UserService {
@Autowired
lateinit var userDao: UserDao
fun selectUserByName(name: String): User {
return userDao.selectUserByName(name)
}
}
11). 创建UserController
@Controller
class UserController {
@Autowired
lateinit var userService: UserService
@RequestMapping("/select")
@ResponseBody
fun selectUserByName(): User {
return userService.selectUserByName("mazaiting")
}
}