<update id="update" parameterType="users">
update users set username = #{username} ,birthday = #{birthday} ,
sex = #{sex} ,address =#{address} where id = #{id}
</update>
<!--
如果采⽤POJO传参,#{} ⾥写的是get⽅法的⽅法名去掉get之后将剩下的单词⾸字⺟变⼩写(例如:getAge对应的是#{age},
getUserName对应的是#{userName}),如果这样的get⽅法不存在会报错。
注意:其实传参数的时候有⼀个属性parameterType,这个属性⽤来指定传参的数据类型,不过这个属性是可以省略的
-->
select 查询语句
select语句和其它语句不同的是:查询会有⼀个结果集对象(ResultSet):
select(查一个,根据主键查询的话,返回的结果一定是一个。) * 需求:根据id查询。 实现: <select id="selectById" resultType="com.xiaofan.mybatis.pojo.Car"> select * from t_car where id = #{id} </select> Object car = sqlSession.selectOne("selectById", 1); 需要特别注意的是: select标签中resultType属性,这个属性用来告诉mybatis,查询结果集封装成什么类型的java对象。你需要告诉mybatis。 resultType通常写的是:全限定类名。
值得注意的是:
输出结果有点不对劲: Car{id=1, carNum='null', brand='宝马520Li', guidePrice=null, produceTime='null', carType='null'} id和brand属性有值。 其他属性为null。 carNum以及其他的这几个属性没有赋上值的原因是什么? select * from t_car where id = 1 执行结果: +----+---------+-----------+-------------+--------------+----------+ | id | car_num | brand | guide_price | produce_time | car_type | +----+---------+-----------+-------------+--------------+----------+ | 1 | 1001 | 宝马520Li | 10.00 | 2020-10-11 | 燃油车 | +----+---------+-----------+-------------+--------------+----------+ car_num、guide_price、produce_time、car_type这是查询结果的列名。 这些列名和Car类中的属性名对不上。 Car类的属性名: carNum、guidePrice、produceTime、carType 那这个问题怎么解决呢? select语句查询的时候,查询结果集的列名是可以使用as关键字起别名的。 <select id="selectById" resultType="com.powernode.mybatis.pojo.Car"> select id,car_num as carNum,brand,guide_price as guidePrice, produce_time as produceTime, car_type as carType from t_car where id = #{id} </select> 起别名之后: +----+--------+-----------+------------+-------------+---------+ | id | carNum | brand | guidePrice | produceTime | carType | +----+--------+-----------+------------+-------------+---------+ | 1 | 1001 | 宝马520Li | 10.00 | 2020-10-11 | 燃油车 | +----+--------+-----------+------------+-------------+---------+
select查询所有:
<select id="selectAll" resultType="com.xiaofan.mybatis.pojo.Car"> select id,car_num as carNum,brand,guide_price as guidePrice, produce_time as produceTime, car_type as carType from t_car </select> List<Object> cars = sqlSession.selectList("selectAll"); 注意:resultType还是指定要封装的结果集的类型。不是指定List类型,是指定List集合中元素的类型。 selectList方法:mybatis通过这个方法就可以得知你需要一个List集合。它会自动给你返回一个List集合。