下文将详细讲解Spring Boot整合MyBatis并自动生成mapper和实体实例的完整攻略。这个过程可以分成以下几个步骤:
- 导入依赖
首先,在pom.xml文件中加入MyBatis和MyBatis Generator的依赖。具体如下:
<dependencies>
<!-- MyBatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<!-- MyBatis Generator-->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.4.0</version>
</dependency>
</dependencies>
- 配置数据库信息
在application.properties文件中配置数据库信息。具体如下:
## 数据库配置
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
- 创建实体类
我们需要创建对应的实体类。这些实体类需要和数据库中的表进行一一对应。具体如下:
public class User {
private Integer id;
private String name;
private String password;
// 省略getter和setter方法
}
public class Order {
private Integer id;
private Integer userId;
private Double price;
// 省略getter和setter方法
}
- 创建Mapper接口
接下来,我们需要创建对应的Mapper接口。这些接口需要使用Mybatis的注解来进行对应的SQL语句操作。具体如下:
@Mapper
public interface UserMapper {
@Select("select id, name, password from user where id = #{id}")
User findById(@Param("id") Long id);
@Insert("insert into user(name, password) values(#{name}, #{password})")
int insert(User user);
@Update("update user set name=#{name}, password=#{password} where id = #{id}")
int update(User user);
@Delete("delete from user where id = #{id}")
int delete(@Param("id") Long id);
@Select("select id, name, password from user")
List<User> findAll();
}
@Mapper
public interface OrderMapper {
@Select("select id, user_id as userId, price from order where id = #{id}")
Order findById(@Param("id") Long id);
@Insert("insert into order(user_id, price) values(#{userId}, #{price})")
int insert(Order order);
@Update("update order set user_id=#{userId}, price=#{price} where id = #{id}")
int update(Order order);
@Delete("delete from order where id = #{id}")
int delete(@Param("id") Long id);
@Select("select id, user_id as userId, price from order")
List<Order> findAll();
}
- 配置MyBatis Generator
接下来,我们需要配置MyBatis Generator。这个工具可以自动生成Mapper和实体类。我们在项目中先创建一个generatorConfig.xml文件。具体如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<context id="default" targetRuntime="MyBatis3Simple">
<property name="javaFileEncoding" value="UTF-8" />
<commentGenerator type="org.mybatis.generator.internal.NullCommentGenerator"/>
<jdbcConnection driverClass="${jdbc.driverClassName}"
connectionURL="${jdbc.url}"
userId="${jdbc.username}"
password="${jdbc.password}">
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<javaModelGenerator targetPackage="com.example.mybatisdemo.model"
targetProject="src/main/java">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<sqlMapGenerator targetPackage="com.example.mybatisdemo.mapper"
targetProject="src/main/resources">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<javaClientGenerator targetPackage="com.example.mybatisdemo.mapper"
targetProject="src/main/java"
type="XMLMAPPER">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<table schema="" tableName="user">
<generatedKey column="id" sqlStatement="JDBC" identity="true" />
</table>
<table schema="" tableName="order">
<generatedKey column="id" sqlStatement="JDBC" identity="true" />
</table>
</context>
</generatorConfiguration>
- 执行MyBatis Generator
最后,我们通过执行MyBatis Generator来生成对应的Mapper和实体类。可以在pom.xml文件中配置MyBatis Generator插件。具体如下:
<build>
<plugins>
<!-- MyBatis Generator插件 -->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.4.0</version>
<configuration>
<verbose>true</verbose>
<overwrite>true</overwrite>
<configurationFile>src/main/resources/generatorConfig.xml</configurationFile>
</configuration>
</plugin>
</plugins>
</build>
配置完成后,在执行mvn mybatis-generator:generate
即可生成对应的文件。
- 使用示例
这里给出一个简单的示例,演示如何在项目中使用Mapper。具体如下:
@RestController
public class UserController {
@Autowired
private UserMapper userMapper;
@GetMapping("/users/{id}")
public User getUserById(@PathVariable Long id){
return userMapper.findById(id);
}
}
在上面的代码中,我们使用了自动生成的UserMapper来查询出对应id的User信息。
另外,如果你想进一步学习Spring Boot整合MyBatis的知识,可以参考这篇文章:「Spring Boot之整合Mybatis拾遗」。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Spring Boot整合mybatis并自动生成mapper和实体实例解析 - Python技术站