springboot项目整合mybatis并配置mybatis中间件的实现

网友投稿 680 2023-01-28

springboot项目整合mybatis并配置mybatis中间件的实现

springboot项目整合mybatis并配置mybatis中间件的实现

记录创建springboot项目并配置mybatis中间件:

资源准备及版本说明

编程工具:IDEA

JDK版本:1.8

Maven版本:Apache Maven 3.6.3

springboot版本:2.4.4

mybatis版本:1.3.2

mysql版本:5.1.48

创建mavem项目

通过IDEA创建很便捷,参考《IDEA创建SpirngBoot项目》。

配置pom.xml

使用mybatis需要添加依赖

org.mybatis.spring.boot

mybatis-spring-boot-starter

1.3.2

完整pom.xml配置如下:

xmlns:xsi="http://w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

4.0.0

org.springframework.boot

spring-boot-starter-parent

2.4.4

org.example

springboot-mybatis

1.0-SNAPSHOT

UTF-8

UTF-8

1.8

1.3.2

5.1.48

org.springframework.boot

spring-boot-starter-web

org.springframework.boot

spring-boot-starter-test

test

org.springframework.boot

spring-boot-starter-jdbc

org.mybatis.spring.boot

mybatis-spring-boot-starter

mysql

mysql-connector-java

${mysql.version}

org.projectlombok

lombok

true

org.springframework.boot

spring-boot-maven-plugin

&lhttp://t;/plugins>

xmlns:xsi="http://w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

4.0.0

org.springframework.boot

spring-boot-starter-parent

2.4.4

org.example

springboot-mybatis

1.0-SNAPSHOT

UTF-8

UTF-8

1.8

1.3.2

5.1.48

org.springframework.boot

spring-boot-starter-web

org.springframework.boot

spring-boot-starter-test

test

org.springframework.boot

spring-boot-starter-jdbc

org.mybatis.spring.boot

mybatis-spring-boot-starter

mysql

mysql-connector-java

${mysql.version}

org.projectlombok

lombok

true

org.springframework.boot

spring-boot-maven-plugin

&lhttp://t;/plugins>

配置application.yml

配置mybatis主要配置数据表映射实体类路径type-aliases-package和数据表映射配置文件路径mapper-locations

完整application.yml配置如下:

创建项目启动文件

在Application启动文件配置扫描持久化层的路径的注解@MapperScan

代码结构

以user表为例子,创建controller目录、dao目录、service目录、model目录以及在resources目录下创建mapper目录用来保存映射xml文件。

完整代码结构如下:

映射实体类User:

持久层UserDao:

注意添加@Repository注解

业务层UserService:

创建根据ID查询记录的接口getById(Long id);

业务层接口实现类UserServiceImpl:

注意添加@Service注解,引入UserDao,实现根据ID`查询记录

控制层UserController:

注入业务层接口,增加测试查询方法getUserById();

映射mapper文件:

其中namespace对应持久化层dao的路径,resultMap为数据表字段与实体映射类属性的关联,type为实体映射类的路径,select查询配置中resultType为查询结果的对象类型路径。

启动项目

启动项目并访问http://localhost:8866/test测试配置情况

application.xml配置文件中增加日志输出sql语句的配置:

重启项目后再次测试接口:

springboot默认使用HikariPool数据库连接池。

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:h5和混合app开发工具(app用h5开发)
下一篇:h5和混合app开发(app原生开发 混合开发 h5开发)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~