Spring Boot整合MyBatis

一、工程创建
在这里插入图片描述
二、添加Druid Spring Boot Starter依赖

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.22</version>
</dependency>

三、在application.properties中配置数据库的基本信息:

spring.datasource.url=jdbc:mysql:///test01?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=******
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

四、创建UserMapper:

public interface UserMapper {

		@Select("select * from t_user")
		List<User> getAllUsers();

		@Results({
            @Result(property = "id", column = "id"),
            @Result(property = "username", column = "name"),
            @Result(property = "address", column = "addr")
		})
    	@Select("select username name,address addr,id from t_user where id=#{id}")
    	User getUserById(int id);

		@Select("select * from t_user where username like concat('%',#{username},'%')")
    	List<User> getUsersByUsername(String username);

		@Insert({"insert into t_user(username,address) values(#{username},#{address})"})
    	@SelectKey(statement = "select last_insert_id()", keyProperty = "id", before = false, resultType = Integer.class)
    	Integer addUser(User user);

		@Update("update t_user set username=#{username},address=#{address} where id=#{id}")
    	Integer updateUserById(User user);

		@Delete("delete from t_user where id=#{id}")
    	Integer deleteUserById(Integer id);

使用@SelectKey注解可以实现主键回填的功能,即当数据插入成功后,插入成功的数据id会赋值到User对象的id属性上。
配置mapper扫描:
a、在每一个mapper上添加@Mapper注解
b、在启动类上添加@MapperScan(basePackages = “com.mybatis.mapper”)
五、mapper映射

public interface UserMapper2 {

    List<User> getAllUsers();

	Integer addUser(User user);

	Integer updateUserById(User user);

	Integer deleteUserById(Integer id);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mybatis.mapper.UserMapper2">
	<select id="getAllUsers" resultType="user">
        select * from t_user
    </select>
    <insert id="addUser">
        insert into t_user (username,address) values (#{username},#{address})
    </insert>
    <update id="updateUserById">
        update t_user set username=#{username},address=#{address} where id=#{id}
    </update>
    <delete id="deleteUserById">
        delete from t_user where id=#{id}
    </delete>
</mapper>

在使用Maven的时候,java目录下的xml资源在项目打包的时候会被忽略掉,所以需要再pom.xml文件中添加如下配置:

<build>
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.xml</include>
            </includes>
        </resource>
        <resource>
            <directory>src/main/resources</directory>
        </resource>
    </resources>
</build>

当然,UserMapper2.xml也可以直接放在resources目录下,这样就不用担心打包时被忽略了,例如在mapper目录中存放mapper文件。
在application.properties中告诉mybatis去哪里扫描mapper:

mybatis.mapper-locations=classpath:mapper/*.xml

【注意】这种方式不需要在pom.xml文件中配置文件过滤。
六、部分源码

@org.springframework.context.annotation.Configuration
@ConditionalOnClass({ SqlSessionFactory.class, SqlSessionFactoryBean.class })
@ConditionalOnSingleCandidate(DataSource.class)
@EnableConfigurationProperties(MybatisProperties.class)
@AutoConfigureAfter({ DataSourceAutoConfiguration.class, MybatisLanguageDriverAutoConfiguration.class })
public class MybatisAutoConfiguration implements InitializingBean {

	@Bean
  	@ConditionalOnMissingBean
  	public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
    	SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
    	factory.setDataSource(dataSource);
    	return factory.getObject();
  	}

	@Bean
  	@ConditionalOnMissingBean
  	public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
    	ExecutorType executorType = this.properties.getExecutorType();
    	if (executorType != null) {
      		return new SqlSessionTemplate(sqlSessionFactory, executorType);
    	} else {
      		return new SqlSessionTemplate(sqlSessionFactory);
    	}
  	}

	@org.springframework.context.annotation.Configuration
  	@Import(AutoConfiguredMapperScannerRegistrar.class)
  	@ConditionalOnMissingBean({ MapperFactoryBean.class, MapperScannerConfigurer.class })
  	public static class MapperScannerRegistrarNotFoundConfiguration implements InitializingBean {
  		@Override
    	public void afterPropertiesSet() {
      		logger.debug(
          		"Not found configuration for registering mapper bean using @MapperScan, MapperFactoryBean and MapperScannerConfigurer.");
    	}
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值