Mybatis的步骤是,获得数据源,获得sqlsessionFactory,获得sqlsession,获得mapper,执行mapper语句。
springboot让我们可以直接使用@mapper注解获得mapper,数据源如果指定了,就用指定的,没有指定就用默认的Hikari数据源(数据源和连接池是一个东西,是用来管理链接的,jdbc访问数据库的第二步,获取链接)sqlsessionFactory和sqlsession被默认配置了。
需要在application.yaml中告诉springboot,mapper文件在哪
mybatis:
mapper-locations: classpath:mybatis/mapper/*.xml
配置文件不变(因为没有设置类型别名,所以resutlType要写类的别名)
<?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.example.springbootdemo3.mapper.TypeMapper">
<select id="querybyid" parameterType="int" resultType="com.example.springbootdemo3.pojo.Type">
select * from type where id=#{id}
</select>
</mapper>
需要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
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<package name="com.example.springbootdemo3.pojo"/>
</typeAliases>
</configuration>
注解版
就是不用写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中还写了这句话,会报错,非注解方法和配置方法只能存在一个。
注解和配置方法两种,比较简单的可以直接写在注解上,难一点的方法可以写在配置文件上