MyBatis查询所有数据
-
查询所有数据
-
编写接口方法:Mapper接口,参数:无,结果:List
-
在com.uestc.mapper创建一个BrandMapper类
public interface BrandMapper { ? /** * 查询所有 */ public List
selectAll(); ? } 2.(编写SQL语句:SQL映射文件)在resources下面的com.uestc.mapper创建一个BrandMapper.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.uestc.mapper.BrandMapper"> <resultMap id="brandResultMap" type="brand"> <result column="brand_name" property="brandName" /> <result column="company_name" property="companyName" /> resultMap> <select id="selectAll" resultMap="brandResultMap"> select * from tb_brand; select> mapper>
3.(执行方法:测试)在test下面创建com.uestc.test.MyBatisTest的类
public class MyBatisTest { ? @Test public void testSelectAll() throws IOException { //1.获取SqlSessionFactory String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); ? //2.获取SqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(); ? //3.获取Mapper接口的代理对象 BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class); ? //4.执行方法 List
brands = brandMapper.selectAll(); System.out.println(brands); ? //5.释放资源 sqlSession.close(); } }
-
实体类属性名和数据库表列名不一致,不能自动封装数据
(1)起别名:在SQL语句中,对不一样的列名起别名,别名和实体类属性名一样。*可以定义
片段,提升复用性 (2)resultMap:定义
完成不一致的属性名和列名的映射。 -