其实只要执行成功了查询语句以后,其他的还是比较容易了,因为基础的语法已经熟悉了。下面开始:
1. Insert
dao代码:
Object insertPerson(Person person);
PersonDao.xml中的sql:
<insert id="insertPerson" parameterType="Person"> insert into person (name,age) values (#{name},#{age}) </insert>
测试代码:
@Test
public void testInsertPerson(){
Person person = new Person();
person.setAge(12);
person.setName("henushang");
int result = session.insert("com.ggg.henushang.dao.PersonDao.insertPerson",person);
session.commit();
Assert.assertEquals(1, result);
}
记住需要自己手动来commit完成事务的提交。
2. Update
dao代码:
void updatePerson(Person person);
PersonDao.xml中的sql:
<update id="updatePerson" parameterType="Person"> update person set name = #{name}, age = #{age} where id = #{id} </update>
测试代码:
@Test
public void testUpdatePerson(){
Person p = session.selectOne("com.ggg.henushang.dao.PersonDao.selectOnePerson",3);
p.setName("updatename");
p.setAge(45);
session.update("com.ggg.henushang.dao.PersonDao.updatePerson", p);
session.commit();
p = session.selectOne("com.ggg.henushang.dao.PersonDao.selectOnePerson",3);
Assert.assertEquals(45, p.getAge());
Assert.assertEquals("updatename", p.getName());
}
3. Delete
dao代码:
void deletePerson(int id);
PersonDao.xml中的sql:
<delete id="deletePerson" parameterType="int"> delete from person where id = #{id} </delete>
测试代码:
@Test
public void testDeletePerson(){
session.update("com.ggg.henushang.dao.PersonDao.deletePerson", 1);
session.commit();
Person p = session.selectOne("com.ggg.henushang.dao.PersonDao.selectOnePerson",1);
Assert.assertNull(p);
}
好了,准备下班回宿舍了~