安装MybatisX
可以提高效率

sql映射文件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"> <!--namespace:名称空间。写接口给的全类名,相当于告诉MyBatis这个配置文件是实现哪个接口的。--> <mapper namespace="com.avb.Mapper.BrandMapper"> <!--resultType=""指定查询数据封装结果的时候使用自定义封装规则--> <select id="selectAll" resultType="brand"> select * from tb_brand; </select> <!--<!–type指定为哪个javaBean自定义封装规则,id是唯一标识–> <resultMap id="mycat" type="smq.javabean.Cat"> <!–id指定主键列的对应规则,column指定哪一列是主键列,property指定cat的哪个属性封装id这个列数据–> <id column="id" property="id"/> <!–普通列–> <result column="cName" property="name"/> <result column="cgender" property="gender"/> <result column="cAge" property="age"/> </resultMap>--> </mapper>
接口文件BrandMapper
package com.avb.Mapper; import com.avb.pojo.Brand; import com.avb.pojo.User; import java.util.List; public interface BrandMapper { List<Brand> selectAll(); }
查询所有
package com.avb.test; import com.avb.Mapper.BrandMapper; import com.avb.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 MybstisTest { @Test public void testSelectAll() throws IOException { //1、获取sqlSessionFactory String rescource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(rescource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //2、获取SqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(); //3、获取Mapper接口的代理对象 BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class); //4、执行方法 List<Brand> brands = brandMapper.selectAll(); System.out.println(brands); //5、释放资源 sqlSession.close(); } }
如果数据库中字段名称和实体类中的属性名称不相同,则不能自动封装数据
解决:给字段起别名
select company_name as company_Name from tb_brand;
浙公网安备 33010602011771号