Springboot通过Mybatis框架集成H2数据库(Springboot版本 2.7.6 java 8)
pom文件引入如下依赖:
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.2.0</version> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency>
以上2个是核心依赖,另外为了使的程序运行,还需要其他依赖,主要有:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency>
application文件定义
spring.application.name=demo4Mybatis server.port=8081 #H2数据库配置 spring.h2.console.enabled=true spring.h2.console.path=/h2 spring.datasource.url=jdbc:h2:~/testdb;NON_KEYWORDS=USER spring.datasource.driver-class-name=org.h2.Driver spring.datasource.username=root spring.datasource.password=test #Mybatis配置 #Mapper文件路径 mybatis.mapper-locations=classpath:/*.xml #数据库初始化schema spring.sql.init.schema-locations=classpath:schema.sql spring.sql.init.mode=always
接下来是程序主体内容,目录如下:
数据实体User定义 POJO
@Getter
@Setter
public class User {
private Long id;
private String username;
private String password;
}
UserMapper定义
@Mapper
public interface UserMapper {
User selectUserByID(Long ind);
void insertUser(User user);
}
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.example.demo4mybatis.service.UserMapper">
<resultMap id="BaseResultMap" type="com.example.demo4mybatis.entity.User">
<id column="id" property="id" jdbcType="BIGINT" />
<result column="username" property="username" jdbcType="VARCHAR" />
<result column="password" property="password" jdbcType="VARCHAR" />
</resultMap>
<select id="selectUserByID" resultMap="BaseResultMap">
SELECT * FROM user WHERE id = #{id}
</select>
<insert id="insertUser">
INSERT INTO user (id, username, password) VALUES (#{id}, #{username}, #{password})
</insert>
</mapper>
数据库初始化Schema定义(必须有,否则执行下面的controller会报数据表不存在)
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user`
(
`id` int PRIMARY KEY,
`username` varchar(255),
`password` varchar(255)
)
Controller定义
@Slf4j
@RestController
@RequiredArgsConstructor
public class UserController {
public final UserMapper userMapper;
@GetMapping(value = "/user")
public User getUserById(@RequestParam(value = "id", required = true) Long id) {
log.info("Get one user {}", id);
return userMapper.selectUserByID(id);
}
@PostMapping(value = "/user")
public void addUser(@RequestBody User user) {
userMapper.insertUser(user);
log.info("Add one user {}", user.getUsername());
}
}