- 分析:接口的方法不需要参数,需要一个集合返回值。
- 注:数据库字段名和pojo类中的属性必须一致、或者起别名
- 建立好项目,注意mapper接口和mapper.xml相对包路径要一致
![在这里插入图片描述](https://img-blog.csdnimg.cn/7667c92cac874c0ca4165ea1ed6b50e2.png)
- 配置好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.ljh.pojo"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///mybatis?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
<environment id="test">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///mybatis?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="com.ljh.mapper"/>
</mappers>
</configuration>
- 编写mapper接口,利用mybatisX生成对应的mapper.xml映射
package com.ljh.mapper;
import com.ljh.pojo.Brand;
import java.util.List;
public interface BrandMapper {
public List<Brand> selectAll();
}
- 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="com.ljh.mapper.BrandMapper">
<resultMap id="brandResultMap" type="brand">
<result column="brand_name" property="brandName"></result>
<result column="company_name" property="companyName"></result>
</resultMap>
<select id="selectAll" resultMap="brandResultMap">
select *
from tb_brand
</select>
</mapper>
- 单元测试
package com.ljh.test;
import com.ljh.mapper.BrandMapper;
import com.ljh.pojo.Brand;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class MybatisTest {
@Test
public void testSelectAll() throws IOException {
String resource = "mybatis-config";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
List<Brand> brands = mapper.selectAll();
System.out.println(brands);
sqlSession.close();
}
}
- 运行结果
![在这里插入图片描述](https://img-blog.csdnimg.cn/635d9d5bd4814375bdb05a1355705647.png)