栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

配置版和注解版 使用mybaits数据库

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

配置版和注解版 使用mybaits数据库

Mybatis的步骤是,获得数据源,获得sqlsessionFactory,获得sqlsession,获得mapper,执行mapper语句。

springboot让我们可以直接使用@mapper注解获得mapper,数据源如果指定了,就用指定的,没有指定就用默认的Hikari数据源(数据源和连接池是一个东西,是用来管理链接的,jdbc访问数据库的第二步,获取链接)sqlsessionFactory和sqlsession被默认配置了。

需要在application.yaml中告诉springboot,mapper文件在哪

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

配置文件不变(因为没有设置类型别名,所以resutlType要写类的别名)




  
      select * from type where id=#{id}
  

 需要mapper接口添加@mapper注解,告诉springboot,这是一个mybaits的接口

或者在主配置类中写mapperscan(),告诉springboot,扫描mapper接口的路径

package com.example.springbootdemo3;

import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.ConfigurableApplicationContext;

@Slf4j
@MapperScan("com.example.springbootdemo3.mapper")
@SpringBootApplication
public class SpringBootDemo3Application {

	public static void main(String[] args) {
		ConfigurableApplicationContext run = SpringApplication.run(SpringBootDemo3Application.class, args);

	}

}
package com.example.springbootdemo3.mapper;

import com.example.springbootdemo3.pojo.Type;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.web.bind.annotation.RequestParam;

@Mapper
public interface TypeMapper {
    public Type querybyid(@RequestParam("id") Integer id);
}

调用的时候直接@autowired即可,我这直接在controller层调用了

    @Autowired
    TypeMapper typeMapper;

    @GetMapping(value = "/querybyid")
    @ResponseBody
//    碰上modelandview会显示什么
    public Type querybyid(@RequestParam("id") int id) {
        return typeMapper.querybyid(id);
    }

想要设置mybaits的配置参数,比如驼峰命名,类型别名,可以直接在application.yaml中配置。

mybatis:
  mapper-locations: classpath:mybatis/mapper/*.xml
  type-aliases-package: com.example.springbootdemo3.pojo

还有一种方式是使用配置文件,在yaml中指定配置文件的位置即可(两种方式不能混用,推荐第一种)

mybatis:
  mapper-locations: classpath:mybatis/mapper/*.xml
 config-location: classpath:mybatis/mapper/mybatis-config.xml



    
        
    


注解版 

就是不用写TypeMapper.xml文件,把sql语句使用@service注解注在接口的方法上即可。

其他的地方不变。

@Mapper
public interface TypeMapper {
    @Select("select * from type where id=#{id}")
    public Type querybyid(@RequestParam("id") Integer id);
}

 如果写了@select注解在application.yaml中还写了这句话,会报错,非注解方法和配置方法只能存在一个。

注解和配置方法两种,比较简单的可以直接写在注解上,难一点的方法可以写在配置文件上

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/970010.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号