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. 配置连接池
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
#德鲁伊 连接池
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
5.做保存,删除,修改时,事务问题
- 在service层添加注解@Transactional,如果不添加,在运行时有异常的情况下,不会回滚,加上后,事务回滚,抛出异常,数据不会保存在数据库中