SpringBoot与mybatis整合-05

1.导入相关jar

1.创建项目时,直接导入相关jar
在这里插入图片描述

注意:在项目中直接导入mysql的版本较高,使用时要降低版本,否则可能会报错

2.第二种在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配置文件,需要指定该文件路径的路径
#mybatis.config-location=classpath:mapper/conf/mybatis-config.xml
#指定mapper.xml文件的路径,如果mapper.xml与接口在一起则不需要该配置
mybatis.mapperlocations=classpath:mapper/*Mapper.xml
#扫面domain包中的实体类并起别名
mybatis.type-aliases-package=com.mr.domain
#日志级别改为debug可以显示sql语句,logging.level后为存放mapper接口的包
logging.level.com.mr.springboot.mapper=debug
##数据源配置
spring.datasource.username=mr_xbb
spring.datasource.password=123
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/mr_xbb
扫描Mapper接口的方法:

1.方法一
在每个mapper接口上添加@Mapper注解

//@Mapper 因为我们没有配置文件中去扫描注解,所以需要添加@Mapper去找这个接口,否则找不到
public interface UserMapper {
    //查询
    List list();
}

2.方法二
在启动类Application的类名上添加@MapperScan(“接口包路径”)

@SpringBootApplication
@MapperScan("com.mr.mapper")
public class Application {

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}
}

3.使用Druid数据库连接池

添加坐标

<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
添加事务

在每个Service实现类上添加@Transactional即可

4.resultType="map"的作用

	<!--List list();查询-->
    <select id="list" resultType="map">
        select * from z_user
    </select>

Mybatis会自动将字段名作为key值,将对应的字段值作为value封装到map中,一条记录有多个字段,产生多个key-value键值对存到一个map对象中,多条记录就会生成多个map对象,多个map对象存到list中返回

猜你喜欢

转载自blog.csdn.net/weixin_44102521/article/details/89318882