原生态mybatis实现增删查改操作
我把整个项目都放这里,大家可以去下载下来自己看一眼,改一下数据库的配置信息就可以了,以及记得去下载lombok插件,不然会因为没有get/set方法报错,或者自己手动生成一下get/set方法也可以,然后emm,有不懂的再问我吧呢.
字段名与属性名不一致的情况
比如我数据库中student表的一个字段名为name,但是我student这个bean中用的是userename属性名对应的name字段名,这就叫字段名与属性名不一致
解决方案:
- 在sql语句中起一个别名:
select name as username from student where id = 1.
- 使用mybatis提供的结果集映射resultMap(很重要)
<!--使用resultMap,这个名字随便写的,唯一就行-->
<resultMap id="studentMapper" type="student">
<!--这个id一般都写上,因为id一般都是主键,他们说写上查询快一些-->
<!--column指的是数据库的字段名,property指的是bean对象中的字段名-->
<id column="id" property="id"></id>
<!--这就用于处理字段名不一致的问题,一致的不用写了-->
<result column="name" property="username"></result>
</resultMap>
<!--通过resultMap查询数据_属性名和字段名不一致-->
<!--此处的resultMap(注意不是resultType哈)写成上面定义的resultMap的id,这样我们 的sql语句查询返回的就是一个resultMap了-->
<select id="selectStudentMapper" resultMap="studentMapper">
select id,name,age from student;
</select>