一、示例说明
基于mybatis的通过xml映射或注解(@Insert、@Delete、@Update、@Select)进行数据层访问。下载完整源码示例《亿级流量Jαva高并发与网络编程实战》的ch11章节目录。
二、代码示例
1)注解方式StuMapper类
package com.xwood.demo.mapper;@b@@b@import java.util.List;@b@@b@import org.apache.ibatis.annotations.Delete;@b@import org.apache.ibatis.annotations.Insert;@b@import org.apache.ibatis.annotations.Select;@b@import org.apache.ibatis.annotations.Update;@b@@b@import com.yanqun.entity.Student;@b@@b@@Mapper@b@public interface StuMapper {@b@ @Insert("insert into student values(#{stuno},#{stuname},#{gradeid})")@b@ public boolean addStu(Student student);@b@ @Delete("delete from student where stuno = #{stuno}")@b@ public boolean deleteStuByStuno(int stuno);@b@ @Update("update student set stuname=#{stuname},gradeid=#{gradeid} where stuno = #{stuno}")@b@ public boolean updateStuByStuno(Student student);@b@ @Select("select * from student")@b@ public List<Student> queryStus() ;@b@ @Select("select * from student where stuno = #{stuno}")@b@ public Student queryStuByStuno(Integer stuno) ;@b@}
2) xml方式 - StudentMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>@b@<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"@b@"http://mybatis.org/dtd/mybatis-3-mapper.dtd">@b@<mapper namespace="com.xwood.demo.mapper.StudentMapper">@b@ <!-- 增 -->@b@ <insert id="addStudent" parameterType="com.yanqun.entity.Student">@b@ insert into student values(#{stuno},#{stuname},#{gradeid})@b@ </insert>@b@ <!-- 删 -->@b@ <insert id="deleteStudentByStuno" parameterType="int" >@b@ delete from student where stuno = #{stuno}@b@ </insert>@b@ <!-- 改 -->@b@ <update id="updateStudentByStuno" parameterType="com.yanqun.entity.Student">@b@ update student set stuname=#{stuname},gradeid=#{gradeid} where stuno = #{stuno}@b@ </update>@b@ <!-- 查 -->@b@ <select id="queryStudents" resultType="com.yanqun.entity.Student" > @b@ select * from student@b@ </select> @b@</mapper>
package com.xwood.demo.mapper;@b@@b@import java.util.List;@b@@b@import com.yanqun.entity.Student;@b@public interface StudentMapper {@b@ public boolean addStudent(Student student);@b@ public boolean deleteStudentByStuno(int stuno);@b@ public boolean updateStudentByStuno(Student student);@b@ public List<Student> queryStudents() ;@b@}