1.创建接口
public interface PersonMapper { public void savePerson(Person person); public void deletePerson(int id); public void updatePerson(Person person); public Person getPersonById(int id); public List<Person> getPersons(); } |
2.写映射文件
<mapper namespace="cn.offcn.mapper.PersonMapper">
<insert id="savePerson" parameterType="Person">
insert into person(name,gender,age,birthday)
values(#{name},#{gender},#{age},#{birthday})
</insert>
<delete id="deletePerson" parameterType="int">
delete from person where id=#{id}
</delete>
<update id="updatePerson" parameterType="Person">
update person set name=#{name},gender=#{gender},age=#{age},birthday=#{birthday}
where id=#{id}
</update>
<select id="getPersonById" parameterType="int" resultType="Person">
select * from person where id=#{id}
</select>
<select id="getPersons" resultType="Person">
select * from person
</select>
</mapper>
这里要注意两个对应:
1.Mapper中的namesapce为接口的全完限定名(包名+接口名)
2.Mapper标签中的<insert> <delete> <update> <select>中的id属性名一定要和接口中所定义的方法名一致
如果有任何一个不对应,就会出现绑定异常
3.最后进行测试
public static void addPerson(Person person){
SqlSession session= MyBatisUtils.getSession();
// PersonMapper接口的代理类的对象
PersonMapper personMapper= session.getMapper(PersonMapper.class);
personMapper.savePerson(person);
session.commit();
MyBatisUtils.close(session);
}
public static List<Person> getPersons(){
SqlSession session= MyBatisUtils.getSession();
// PersonMapper接口的代理类的对象
PersonMapper personMapper= session.getMapper(PersonMapper.class);
List<Person> personList=personMapper.getPersons();
session.commit();
MyBatisUtils.close(session);
return personList;
}
以上
原文:https://www.cnblogs.com/zhonggongjavastudy/p/13591278.html