您的位置:首页 > 编程语言 > Java开发

springboot-mybatis 整合_07

2019-02-11 21:34 267 查看
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_44100514/article/details/87004886

1.导入相关jar

  • 创建项目时,直接导入相关jar

    注意:在项目中直接导入mysql的版本较高,使用时要降低版本,否则可能会报错
  • 第二种在pom.xml中导入相关jar
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>

2.在application.properties中配置

  • 注意:开启驼峰命名法,如果不开启,会造成查询条数,显示数据时为空
# mybatis 配置
#使用mybatis配置文件,需要指定该文件的文件路径
#指定mapper.xml文件的路径,如果mapper.xml与接口在一起则不需要该配置
#扫描pojo包中的实体类并起别名
#日志级别改为debug可以显示sql语句,logging.level后为存放mapper接口的包
mybatis.mapper-locations=classpath:mapper/*Mapper.xml
mybatis.type-aliases-package=com.mr.pojo
logging.level.com.mr.mapper=debug
# 开启驼峰命名法 mybatis.configuration.map-underscore-to-camel-case: true
mybatis.configuration.map-underscore-to-camel-case=true

#配置数据源
spring.datasource.username=用户名
spring.datasource.password=密码
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/数据库名

3.做简单查询时

controller,service,mapper mapper接口应要添加注解@Mapper,不然会找不到你的mapper,或者在启动类上添加@MapperScan(“com.mr.mapper”)

4. 配置连接池

  • pom.xml中添加坐标
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
  • application.properties
#德鲁伊 连接池
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

5.做保存,删除,修改时,事务问题

  • 在service层添加注解@Transactional,如果不添加,在运行时有异常的情况下,不会回滚,加上后,事务回滚,抛出异常,数据不会保存在数据库中
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: