springboot+mybatis 最简单配置是怎样的,谢谢!
https://start.spring.io/
这个官网可以新建一个最简单项目,参考一下
https://start.spring.io/ 这个是spring官网快速构建一个项目,然后将以下配置拷贝至application.properties中。
#数据库配置
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
mybatis.config-location=classpath:mybatis-config.xml
@Component
就是java的pojo对象,需要自动生成实体的get和set方法,因为在对mysql实现CRUD会自动去封装对象也就会自动去调用实体的get和set方法。
最简单的配置方式如下:
1.在pom.xml中添加依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
2.在application.properties中添加如下配置:
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/db_name?serverTimezone=UTC&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
mybatis.mapper-locations=classpath:mapper/*.xml
其中,可以根据自己的mysql配置情况,修改url、username和password参数。
3.在和启动类同级的位置创建mapper文件夹,在该文件夹中创建对应的Mapper接口和对应的XML文件,示例代码:
Mapper接口:
@Mapper
public interface UserMapper {
@Insert("insert into user(name, age) values(#{name}, #{age})")
int addUser(User user);
@Select("select * from user where id = #{id}")
User getUserById(@Param("id") int id);
@Select("select * from user")
List<User> getAllUser();
}
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.springboot.mapper.UserMapper">
<insert id="addUser" parameterType="com.example.springboot.entity.User">
insert into user(name, age)
values (#{name}, #{age})
</insert>
<select id="getUserById" parameterType="int" resultType="com.example.springboot.entity.User">
select * from user where id = #{id}
</select>
<select id="getAllUser" resultType="com.example.springboot.entity.User">
select * from user
</select>
</mapper>
4.在启动类中添加注解:
@SpringBootApplication
@MapperScan(basePackages = "com.example.springboot.mapper")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
其中,@MapperScan注解标注的是Mapper接口所在的包名。
5.至此,配置完成,可以在Controller中依赖注入Mapper接口,进行相关的数据库操作即可。