查询结果的列名和java对象的属性名对应不上怎么办?
第⼀种⽅式:as 给列起别名
第⼆种⽅式:使⽤resultMap进⾏结果映射
第三种⽅式:是否开启驼峰命名⾃动映射(配置settings)
使⽤resultMap进⾏结果映射:
* 查询所有的Car信息。使用resultMap标签进行结果映射。 List<Car> selectAllByResultMap();
<!--
1.专门定义一个结果映射,在这个结果映射当中指定数据库表的字段名和Java类的属性名的对应关系。
2. type属性:用来指定POJO类的类名。
3. id属性:指定resultMap的唯一标识。这个id将来要在select标签中使用。
-->
<resultMap id="carResultMap" type="Car">
<!--如果数据库表中有主键,一般都是有主键,要不然不符合数据库设计第一范式。-->
<!--如果有主键,建议这里配置一个id标签,注意:这不是必须的。但是官方的解释是什么呢?这样的配置可以让mybatis提高效率。-->
<id property="id" column="id"/>
<!--<result property="id" column="id"/>--> 这个也可以使用,但是效率较低
<!--property后面填写POJO类的属性名-->
<!--column后面填写数据库表的字段名-->
<result property="carNum" column="car_num" javaType="java.lang.String" jdbcType="VARCHAR"/>
<!--如果column和property是一样的,这个可以省略。-->
<!--<result property="brand" column="brand"/>-->
<result property="guidePrice" column="guide_price"/>
<result property="produceTime" column="produce_time"/>
<result property="carType" column="car_type" javaType="string" jdbcType="VARCHAR"/>
</resultMap>
<!--select标签的resultMap属性,用来指定使用哪个结果映射。resultMap后面的值是resultMap的id-->
<select id="selectAllByResultMap" resultMap="carResultMap">
select * from t_car
</select>
@Test
public void testSelectAllByResultMap(){
SqlSession sqlSession = SqlSessionUtil.openSession();
CarMapper mapper = sqlSession.getMapper(CarMapper.class);
List<Car> cars = mapper.selectAllByResultMap();
cars.forEach(car -> System.out.println(car));
sqlSession.close();
}
第三种⽅式:是否开启驼峰命名⾃动映射(配置settings)
使⽤这种⽅式的前提是:
属性名遵循Java的命名规范,数据库表的列名遵循SQL的命名规范。
Java命名规范:⾸字⺟⼩写,后⾯每个单词⾸字⺟⼤写,遵循驼峰命名⽅式。
SQL命名规范:全部⼩写,单词之间采⽤下划线分割。
如何启⽤该功能,在mybatis-config.xml⽂件中进⾏配置:
<!--放在properties标签后⾯-->
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
返回总记录条数:因为返回的类型是int /long……等类型,不是Map类型
* 获取Car的总记录条数。 Long selectTotal(); <!--<select id="selectTotal" resultType="java.lang.Long"> 或者 --> <!--<select id="selectTotal" resultType="_long"> --> <!--<select id="selectTotal" resultType="long"> --> select count(*) from t_car </select>