1.数据库与java pojo 属性映射问题(字段名与属性名不一致)
方式一:可以在sql语句中使用别名规则
select u_id as uId,u_name as uName, sex sex,t_id as tId from tb_student
方式二:如果遵守驼峰命名规则的,可以在全局配置文件中,开启驼峰命名规则
<setting name="mapUnderscoreToCamelCase" value="true"/>-->
方式三:使用<resultMap>标签映射封装结果集
<resultMap id="myStu" type="com.itheima.pojo.TbStudent"> <id column="u_id" property="uId"></id> <result column="u_name" property="uName"></result> <result column="sex" property="sex" ></result> <result column="t_id" property="tId"></result> </resultMap>
2.使用别名,在全局配置文件中
<typeAliases> <!--别名,如果使用包,默认类的名,不区分大小写--> <package name="com.itheima.pojo"/> </typeAliases>
3.获取自增主键的值
支持自增主键的mysql,sql Server,会使用原生的jdbc中的一个方法getGeneratedKeys()方法可以返回自增主键。
具体实现是在插入的sql语句上加入
userGeneratedKeys="true"-----使用自增主键获取主键值策略
keyProperty="uId" ------指定对应的主键属性,即mybatis获取到主键值以后,将这个值封装给Javabean中的哪个属性。
<insert id="add" parameterType="com.itheima.pojo.TbStudent" useGeneratedKeys="true" keyProperty="ud"> insert into tb_student (u_name,sex,t_id) values (#{uName},#{sex},#{tId})I </insert>
TbStudent tbStudent = new TbStudent(); tbStudent.setuName("赵六"); tbStudent.setSex("男"); tbStudent.settId(101); tbStudentMapper.add(tbStudent); System.out.println(tbStudent.getuId());
4.获取自增主键的值
5.关于参数的问题
5.1如果传入单个参数是,#{名字} ,花括号里的名字可以随意
5.2如果传入的参数不是单个且非对象时
使用#{param1},#{param2}
<select id="getStuBySome" resultMap="myStu"> select * from tb_student where u_name=#{param1} and t_id=#{param2} </select>
或者在接口上的传入的参数
//多参数查询 public TbStudent getStuBySome(@Param(value = "uName") String name,@Param(value = "tId") int tid);
5.3如果传入的参数是对象,则可以使用pojo的属性传参
//传入对象查询 public TbStudent getStuByPojo(TbStudent student);
<!--传入对象查询,直接可以写pojo的属性--> <select id="getStuByPojo" resultMap="myStu"> select * from tb_student where u_name=#{uName} and t_id=#{tId} </select>
5.4如果传入的参数是map
//传入的参数是map
public TbStudent getStuByMap(Map<String, Object> map);
<!--传入的参数是map--> <select id="getStuByMap" parameterType="map" resultMap="myStu"> select * from tb_student where u_name=#{uName} and t_id=#{tId} </select>
Map<String ,Object> map = new HashMap<String, Object>(); map.put("uId",1); map.put("uName","zhangsan"); map.put("tId",102); tbStudentMapper.getStuByMap(map);