-
什么是xml映射 MyBatis提供了注解定义SQL与Mapper接口的映射关系。但是注解不能解决复杂的映射关系,例如sql拼接,所以需要使用xml映射。 -
helloWorld程序 文件结构
someMapper.xml
<?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="cn.tedu.mapper.DemoMapper">
<select id="test" resultType="java.lang.String">
select 'hello world'
</select>
</mapper>
- 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
@Bean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource,
@Value("${mybatis.mapper.location}") Resource[] mapperLocation)
throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
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
|