【SpringBoot】7 数据库(MySQL&MyBatis)
在Spring Boot中,要使用MySQL数据库和MyBatis,你需要做以下几步:
- 添加依赖到
pom.xml
:
<dependencies>
<!-- Spring Boot Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- Spring Boot Starter for MyBatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<!-- MySQL Connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
- 在
application.properties
或application.yml
中配置数据库连接信息:
spring.datasource.url=jdbc:mysql://localhost:3306/your_database?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=yourpassword
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=com.yourpackage.model
- 创建实体类(Model)和映射接口(Mapper):
// Entity
package com.yourpackage.model;
public class User {
private Integer id;
private String name;
// getters and setters
}
// Mapper
package com.yourpackage.mapper;
public interface UserMapper {
User selectUserById(Integer id);
// 其他数据库操作方法
}
- 创建Mapper XML文件,例如
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.yourpackage.mapper.UserMapper">
<select id="selectUserById" parameterType="Integer" resultType="User">
SELECT * FROM users WHERE id = #{id}
</select>
</mapper>
- 在Spring Boot主类或配置类中启用MyBatis扫描:
package com.yourpackage;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.yourpackage.mapper")
public class YourApplication {
public static void main(String[] args) {
SpringApplication.run(YourApplication.class, args);
}
}
- 使用Mapper进行数据库操作:
package com.yourpackage.service;
import com.yourpackage.mapper.UserMapper;
import org.springframework.beans.
评论已关闭