1.首先要有一个namespace为接口的全类名的映射文件,
该例中是/hy_demo/src/main/resources/mybatis/mapper/DemoMapper.xml
2.然后在mybatis的容器(就是总的配置文件 mybatis-config.xml)里的mappers标签内
引入第1步中的映射文件,这里是 mybatis/mapper/DemoMapper.xml
<mappers>
<mapper resource="mybatis/mapper/DemoMapper.xml" />
<mapper resource="mybatis/mapper/User01DemoMapper.xml"/>
</mappers>
application.properties里要加入 mybatis配置
mybatis.config-location=classpath:mybatis-config.xml
3.定义mapper接口(注意mapper接口中不要忘了 @Mapper)
com.haoyi.demo.mapper.DemoMapper.java
@Mapper
public interface DemoMapper {
int countByExample(DemoExample example);
List<Demo> selectByExample(DemoExample example);
Demo selectByPrimaryKey(Integer id);
int updateByExampleSelective(@Param("record") Demo record, @Param("example") DemoExample example);
}
4.通过dao层调用mapper接口方法
@Service
public class DemoDao {
// 注入
@Autowired
private DemoMapper demoMapper;
@TargetDataSource(name = "ds1")
public void addDemo(Demo demo){
demoMapper.insertSelective(demo);
}
@TargetDataSource(name = "ds1")
public List<Demo> selectALLDemo(){
DemoExample example = new DemoExample();
return demoMapper.selectByExample(example);
}
}
5.开始在 DemoMapper.xml 写具体的sql操作。
注意:5.1 各个select,insert 等 标签的id属性同时必须与接口中的方法名一一对应
5.2 也可以配置生成器,利用mybatis-generator自动生成代码。
方式一:https://note.youdao.com/web/#/file/WEBa5345af661de04c4bf5e733cf5615c0c/note/WEB0ece1a0a389da542e4cd8a7265b8127a/
方式二:mybatis-generator.properties/generatorConfig.xml