springboot接入mybatis管理数据库
springboot接入mybatis管理数据库
-
1.创建springboot项目(使用开发工具类似IDEA新建Springboot项目)
-
2.pom依赖引入
<!-- mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <!-- mybatis-spring-boot-starter --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>${mybatis.version}</version> </dependency>
-
3.配置文件(application.yml)
# 数据库配置 spring: datasource: # 驱动 driver-class-name: com.mysql.cj.jdbc.Driver # url url: jdbc:mysql://xxx:3306/second_kill?characterEncoding=utf-8&useSSL=false # 用户名 username: xxx # 密码 password: xxx dbcp2: # 验证查询 validation-query: select 1 from dual # MyBatis mybatis: # 包别名配置 type-aliases-package: com.kinson.springboot.domain # mapper xml位置配置 mapper-locations: classpath:/secondKill/*.xml # 控制台打印sql(https://www.cnblogs.com/kingsonfu/p/9245731.html) configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
-
4.启动类加MapperScan注解
@SpringBootApplication // 多个以逗号分隔 @MapperScan({"com.kinson.springboot.mapper", "xxx"}) public class SecondKillProSpringboot { public static void main(String[] args) { SpringApplication.run(SecondKillProSpringboot.class, args); } }
-
5.新加数据库表映射类
public class User { private Integer id; private String userName; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } }
-
6.新增对应的Mapper类
public interface UserMapper {
/** * 查询所有用户 * * @return */ List<User> selectUserList();
}
-
7.新增对应Mapper的映射xml文件
<select id="selectUserList" parameterType="User" resultMap="UserResult"> select * from user </select>
-
8.之后就可以使用mapper在service注入使用了
Github源码:springboot-mybatis