什么是xml映射
MyBatis提供了注解定义SQL与Mapper接口的映射关系。但是注解不能解决复杂的映射关系,例如sql拼接,所以需要使用xml映射。
helloWorld程序
文件结构
someMapper.xml
select 'hello world'
namespace对应DemoMapper地址id对应方法名,此处是demomapper中的test方法resultType对应方法的返回值,test返回值为String
DemoMapper
package cn.tedu.mapper;
import org.apache.ibatis.annotations.Select;
public interface DemoMapper {
@Select("select empno,ename,sal,deptno from emp where empno=1;")
String hello();
String test();
}
MybatisConfig.java
//配置SqlSessionFactory的作用是告诉mybatis如何找到目标数据库
@Bean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource,
@Value("${mybatis.mapper.location}") Resource[] mapperLocation)
throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
//将所有的Mapper映射xml文件注入给MyBatis
bean.setMapperLocations(mapperLocation);
return bean.getObject();
}
@Value("${mybatis.mapper.location}") Resource[] mapperLocation获取映射关系xml,从jdbc.properties中获取bean.setMapperLocations(mapperLocation);注入MyBatis
jdbc.properties
db.driver=com.mysql.cj.jdbc.Driver db.url=jdbc:mysql://localhost:3306/newdb3?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true db.username=root db.password= db.maxActive=10 db.initialSize=2 mybatis.mapper.location=classpath:mappers/*.xml



