1. select的映射
- <select id="selectPerson" parameterType="int" resultType="hashmap">
- select id, name, sex, updateTime from person where id =#{id};
- </select>
a) #{id}:创建预编译语句参数,占位符
b) parameterType:参数的类型,int类型
c)resultType:返回的结果集,封装为hashMap
- public Map<String, Object> selectPersonById(int id) {
- SqlSession session = DbFactory.getInstance().openSession();
- Map<String, Object> m = (Map<String, Object>) session.selectOne("com.yjq.entity.Person.selectPerson", id);
- session.commit();
- session.close();
- return m;
- }
- {id=4, sex=f, NAME=zql, updateTime=2013-12-10 14:18:11.0, SEX=f, name=zql, ID=4, UPDATETIME=2013-12-10 14:18:11.0}
d) 结果集为啥有大小写的key2份?神奇的mybatis啊。
2. insert,update,delete的映射
- <insert id="insertPerson" parameterType="com.yjq.entity.Person" useGeneratedKeys="true" keyProperty="id"> <!-- 将自增主键生成的值回写到对象 -->
- insert into person(name, sex, updateTime) values(#{name}, #{sex}, #{updateTime});
- </insert>
- <delete id="deletePerson" parameterType="int">
- delete from person where id=#{id};
- </delete>
- <update id="updatePerson" parameterType="com.yjq.entity.Person">
- update person set name=#{name}, sex=#{sex}, updateTime=#{updateTime} where id=#{id};
- </update>
a) parameterType="com.yjq.entity.Person":对象参数,#{name}表示Person对象的name属性。
b) useGeneratedKeys="true" keyProperty="id":只存在于insert命令,写这2个参数会将主键自增长的值回写到传入的参数对象。
- public Person insertPerson(Person p) {
- SqlSession session = DbFactory.getInstance().openSession();
- session.insert("com.yjq.entity.Person.insertPerson", p);
- session.commit();
- session.close();
- return p;
- }
- PersonDao dao = new PersonDao();
- Person p = new Person();
- p.setName("zql");
- p.setSex("f");
- p.setUpdateTime(new Date());
- System.out.println("------" + p.getId());
- dao.insertPerson(p);
- System.out.println(p.getId());
c) 返回值:insert,update,delete方法均返回int参数,表示操作了多少条数据
- int result = session.update("com.yjq.entity.Person.updatePerson", p);
d) 假设数据库不支持自增id,mybatis可以生成随机主键
- <insert id="insertPerson2" parameterType="com.yjq.entity.Person">
- <selectKey keyProperty="id" resultType="int" order="BEFORE"> <!-- 生成随机id数 -->
- select CONVERT(RAND()*1000000,SIGNED) a from dual;
- </selectKey>
- insert into person(id, name, sex, updateTime) values(#{id}, #{name}, #{sex}, #{updateTime});
- </insert>
posted @
2016-07-27 11:46
海米傻傻
阅读(
212)
评论()
编辑
收藏
举报