SpringBoot整合Mybatis

SpringBoot整合Mybatis

方式一:使用Annotation自动化集成

当我按照网上的教程配置后,很简单嘛,基本上啥也不用干,配置个

server:
  address: localhost
  port: 7777

#db

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test2
    username: root
    password: zhw
    type: com.alibaba.druid.pool.DruidDataSource



#mybatis
mybatis:
  type-aliases-package: org.rana.example.annotation.entity

就完事了。

然而,提示

Caused by: java.lang.IllegalArgumentException: Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required

原因是mybatis在某个版本后取消了sqlSessionFactory的自动注入,需要显示注入。

然而设置这玩意儿是需要设置dataSource的,于是dataSource也得显示声明

@Configuration
public class MybatisConfig {


    @Autowired
    private DataSourceProperties dataSourceProperties;


    @Bean(name = "dataSource")
    public DataSource dataSource() {

        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(dataSourceProperties.getUrl());
        System.out.println(dataSourceProperties.getUrl());
        dataSource.setDriverClassName(dataSourceProperties.getDriverClassName());
        dataSource.setUsername(dataSourceProperties.getUsername());
        dataSource.setPassword(dataSourceProperties.getPassword());

        return dataSource;

    }

    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource());
        return sqlSessionFactoryBean.getObject();
    }
}

这样子基本的配置就完成了

@Mapper
public interface UserMapper {


    @Insert("INSERT INTO user (username,email) VALUES (#{username},#{email})")
    int insert(User user);

    @Select("SELECT * FROM user WHERE id = #{id}")
    User selectById(int id);

}

只需要再Mapper上加上@Mapper的Annotation,然后在Application中能够让MapperScan扫到就行了。

这时,我想把事务也加上去,然而经过我的测试,事务默认也自动注入了。只需要再你想要用事务的地方使用@Transactional即可。

方式二:使用传统方式集成

传统方式就没什么好说的了,除了因为没有引入mybatis-spring-boot-starter,需要手动添加许多包之外,跟用Spring集成是一毛一样的。

@SpringBootApplication
@ComponentScan("org.rana.example.annotation")
@ImportResource(locations = {"applicationContext*.xml"})
public class Application implements EmbeddedServletContainerCustomizer {

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

    @Override
    public void customize(ConfigurableEmbeddedServletContainer container) {
        container.setPort(7777);
    }
}

只需要再Application或是其他配置类中使用@ImportResource引入spring配置文件即可。

Comments are closed.