1.File--?New--?Module 更改URL为 https://start.aliyun.com/
此处以MySQL为例
2.MySQL数据库设计
数据库名:springboot 表名 :t_user
3.项目代码
项目结构
package com.ntvu.springbootmybatis.entity; import lombok.Data; /** * @Data注解,使用lombok自动生成get、set、toString等方法。 */ @Data public class User { private Integer id ; private String uname; private Integer age; }
注:使用lombok 须在pom.xml加入dependency 无需加版本号
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <scope>provided</scope> </dependency>
UserMapper
package com.ntvu.springbootmybatis.mapper; import com.ntvu.springbootmybatis.entity.User; import org.apache.ibatis.annotations.Mapper; import org.springframework.stereotype.Repository; import java.util.List; @Mapper @Repository public interface UserMapper { public List<User> findAll(); }
项目自动生成application.properties全部内容注释,此处使用application.yml,两种配置文件都可以
# datasource
spring:
datasource:
# 连接本地mysql可省略端口号
url: jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
#mybatis
mybatis:
mapper-locations: classpath:mapper/*Mapper.xml #mapper映射文件
type-aliases-package: com.ntvu.springbootmybatis.entity #UserMapper.xml中扫包的别名(user)配置
# config-location: #指定mybatis的核心配置文件
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.ntvu.springbootmybatis.mapper.UserMapper"> <select id="findAll" resultType="user"> select * from t_user </select> </mapper>
SpringbootMybatisApplicationTests
package com.ntvu.springbootmybatis; import com.ntvu.springbootmybatis.entity.User; import com.ntvu.springbootmybatis.mapper.UserMapper; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.util.List; @SpringBootTest class SpringbootMybatisApplicationTests { @Autowired private UserMapper userMapper; @Test public void testFindAll() { List<User> list = userMapper.findAll(); System.out.println(list); } }
运行结果
原文:https://www.cnblogs.com/kimit/p/15134088.html