springboot学习之路之集成MyBatis

前言

springboot集成Mybatis的方法有多种,本文的集成方式是基于注解配置Mybatis,使用Druid数据库连接池,未使用过Druid的可以看我的另一篇文章 springboot学习之路之使用Druid数据库连接池 

使用

1.在pom.xml文件中添加Mybatis依赖

<dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2 </version>
 </dependency>

2. 在application.yml文件里添加配置,让Mybatis可以找到你的实体类

注:将参数替换成你存放实体类的包名

mybatis:
  type-aliases-package: com.dyman.personalwebsite.entity

3.编写Mybatis配置类

@Configuration
//加上这个注解,使得支持事务
@EnableTransactionManagement
public class MybatisConfig implements TransactionManagementConfigurer {
    @Autowired
    private DataSource dataSource;

    @Override
    public PlatformTransactionManager annotationDrivenTransactionManager() {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactoryBean() {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);

        try {
            return bean.getObject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
@Configuration
// 因为这个对象的扫描,需要在MyBatisConfig的后面注入,所以加上下面的注解
@AutoConfigureAfter(MybatisConfig.class)
public class MybatisMapperScannerConfig {
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        //获取之前注入的beanName为sqlSessionFactory的对象
        mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
        //指定xml配置文件的路径
        //包名为*mapper接口的路径
        mapperScannerConfigurer.setBasePackage("com.dyman.mybatis.mapper");
        return mapperScannerConfigurer;
    }
}

4.编写Mapper接口,加@Mapper注解是为了让springboot可以寻找到这个类

@Mapper
public interface UserLoginMapper
{
    /**
     * 根据用户名与密码查询用户
     * @param id 用户id
     * @return 用户登陆实体类
     */
    @Select("select * from user_login where id = #{id}")
    UserLogin selectUserById(@Param("id") int id);
}

5.在Application启动类上添加@MapperScan注解

@ServletComponentScan
@SpringBootApplication
@ComponentScan
@MapperScan("com.dyman.mybatis.mapper")
public class PersonalwebsiteApplication {

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

 6.在Controller执行方法从数据库获取数据并展示在页面

@Controller
public class HomepageController
{
    @Autowired
    private UserLoginMapper userLoginMapper;

    @GetMapping("/homepage/{id}")
    public ModelAndView homepage(@PathVariable int id)
    {
        ModelAndView mav = new ModelAndView("homepage");
        UserLogin userLogin = userLoginMapper.selectUserById(1);
        mav.addObject("user1", userLogin.getUserName());
        return mav;
    }
}    
<!DOCTYPE html>
<html lang="en"
      xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
<title>首页</title>
</head>
<body>
<div th:text="${user1}"></div>
</body>
</html>
结果展示


猜你喜欢

转载自blog.csdn.net/Dyman_/article/details/80998371
今日推荐