通知
此博客运行在jpress系统上,如果你喜欢此博客模板,请加QQ群:1061691290(whimurmur模板/jpress插件),免费下载使用

尚硅谷springboot学习33-整合mybatis

983人浏览 / 0人评论 | 作者:whisper  | 分类: springboot  | 标签: 框架  /  springboot  | 

作者:whisper

链接:http://proprogrammar.com:443/article/357

声明:请尊重原作者的劳动,如需转载请注明出处


  引入mybatis依赖(还要引入mysql和jdbc依赖)

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

  步骤:

​   1)、配置数据源相关属性(见上一节Druid)

  ​ 2)、给数据库建表(见上上一节jdbc):department,employee

  ​ 3)、创建表对应的JavaBean:Department,Employee

  使用注解版mybatis

//指定这是一个操作数据库的mapper
@Mapper
public interface DepartmentMapper {

    @Select("select * from department where id=#{id}")
    public Department getDeptById(Integer id);

    @Delete("delete from department where id=#{id}")
    public int deleteDeptById(Integer id);

    @Options(useGeneratedKeys = true,keyProperty = "id")
    @Insert("insert into department(departmentName) values(#{departmentName})")
    public int insertDept(Department department);

    @Update("update department set departmentName=#{departmentName} where id=#{id}")
    public int updateDept(Department department);
}

  自定义MyBatis的配置规则;给容器中添加一个ConfigurationCustomizer;

@org.springframework.context.annotation.Configuration
public class MyBatisConfig {

    @Bean
    public ConfigurationCustomizer configurationCustomizer(){
        return new ConfigurationCustomizer(){

            @Override
            public void customize(Configuration configuration) {
                configuration.setMapUnderscoreToCamelCase(true);
            }
        };
    }
}

  使用MapperScan批量扫描所有的Mapper接口;

@MapperScan(value = "com.atguigu.springboot.mapper")
@SpringBootApplication
public class SpringBoot06DataMybatisApplication {

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

  使用配置文件的方式

  指定配置文件和mapper文件的位置

mybatis:
  config-location: classpath:mybatis/mybatis-config.xml 指定全局配置文件的位置
  mapper-locations: classpath:mybatis/mapper/*.xml  指定sql映射文件的位置

 

  

  

  对应的java类

  这样调用上面的java类方法,就能使用mybatis操作数据了


亲爱的读者:有时间可以点赞评论一下

点赞(0) 打赏

全部评论

还没有评论!