香洲区建设局网站做游戏推广怎么找客户
首先是 增 ,我们要在数据库中增加一个数据
先来看看我们之前的插入语句
<insert id="insertRole">insert into try(id,name,age) values(3,'nuonuo',20)</insert>
请注意,我们这里的 insert 是固定的,但在实际的业务场景中,我们需要通过输入不同的代码,传递给数据库,意思就是 数据是不固定的。在
jdbc中,我们通过 ? 占位符可以实现传递 ,那么在 ,mybatis中我们可以使用 #{}来实现站位的功能,
同时,mybatis优于jdbc的点就是因为rom映射,因此我们必须将#{}中填写对应的字段来实现匹配。
改造后的insert语句如下
<insert id="insertRole">insert into try(id,name,age) values(#{id},#{name},#{age})</insert>
请看一下我们的pojo类
package com.chenchen.pojo;public class role {private Integer id;private String name;private Integer age;public role(Integer id, String name, Integer age) {this.id = id;this.name = name;this.age = age;}public role() {}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}@Overridepublic String toString() {return "role{" +"id=" + id +", name='" + name + '\'' +", age=" + age +'}';}
}
首先我们来解释一下运行原理:
程序调用 insertRole这个id的插入语句,就会自动匹配 pojo的属性类 与字段,然后传入数据库,中中间会使用 get方法获取属性值,因此务必 字段名与属性名一致
我们来写个类测试一下
首先我们需要创建一个 role对象
@Testpublic void insertTest(){
// 首先我们需要创建一个role对象,这样才能实现映射role role = new role(5,"可爱的绘梨衣",18);sqlSession.insert("insertRole",role);sqlSession.commit();sqlSession.close();}
这样就可以了,并且实现映射
同时我们可以使用map集合来做,不在记录
然后是删除,那么我们就需要一个delete语句在mapper中
<delete id="deleteRole">delete from try where id = #{id}</delete>
public void deleteRole(){System.out.println("删除的数量"+sqlSession.delete("deleteRole", 1));sqlSession.commit();sqlSession.close(); }
请注意 这里的 id 参数只有一个,所以可以任意的写匹配符号
然后是修改语句 ,如上 请完成mapper的补充
<update id="updateRole">update try set name = #{name} where id = #{id}</update>
public void upd(){role role = new role(2,"莫山山",18);sqlSession.update("updateRole",role);sqlSession.commit();
}
请注意,这里我们更新数据库中的数据只有两种方式,一种是传入一个参数,一种是传入一个完整的对象,但是没关系,即使我们传入一个完整的对象,后面的update语句也会根据get方法获取到对应的数据的。
然后是查找
查找分为查一个和查多个
首先是查一个
<select id="selectRole" resultType="com.chenchen.pojo.role" >select * from try where id = #{id}</select>
public void select(){role role = sqlSession.selectOne("selectRole",5);System.out.println(role);sqlSession.commit();sqlSession.close();
}
请注意,从数据库中获得的对象一定是一个数据集,但是mybatis需要将数据集转换为对应的pojo实例,所以我们必须在select中确定role的类型
然后是查所有
public void selectAll(){List<role> list = sqlSession.selectList("selectAll",role.class);System.out.println(list); }
<select id="selectAll" resultType="com.chenchen.pojo.role">select * from try </select>
请注意,这个时候返回的结果集是一个数组,用数组来承接形成后的对象真的很方便
这就是全过程
我们来总结一下
首先使用 #{id}的占用符在XXmapper.xml中编写对应的 crud语句,如果是查询语句请设置好类型,然后写好id 在程序中拿到id,创建好对象,然后调用对应的方法就可以
我们再来说说namespace的作用
namespace可以区分不同的配置环境