MyBatis映射器元素
MyBatis映射器元素
<select id = "countFirstName" parameterType = "string" resultType = "int"> select count(*) as total from t_user where name like concat(#{firstName},'%') </select>
public class Role{ private Long id; private String roleName; private String note; public Long getId(){ return id; } public void setId(Long id){ this.id = id; } public String getRoleName(){ return roleName; } public void setRoleName(String roleName){ this.roleName = roleName; } public String getNote(){ return note; } public void setNote(String note){ this.note = note; } }
结果集映射的javabean已经写好了,接下来就是自动映射的语句;
<select parameterType = "id" id = "getRole" resultType = "com.learn.chapter4.pojo.Role"> select id, role_name as roleName, note from t_note where id = #{id} </select>
再提供一个方法;
public Role getRole(Long id);
接下来是关于传递参数的映射,首先,如何传递多个参数呢?这里有三个方法,是根据你的参数的个数来决定的,map方法,注解方法和javabean方法,其中,map方法因为可读性较差,在这里就不列举了,下面是注解的方式来传递;
public List<Role> findRoleByAnnotation(@Param("roleName") String rolename,@Param("note") String note);
我们把映射器的xml修改为无需定义参数类型,
<select id = "findRoleByAnnotation" resultMap = "roleMap"> select id ,role_name,note from t_role where role_name like concat ('%',#{roleName},'%') and note like concat('%',#{note},'%') </select>
<resultMap id = "roleResultMap" type = "com.learn.chapter4.pojo.Role"> <id property = "id" column = "id"> <result property = "roleName" column = "role_name"> <result property = "note" column = "note"/> </resultMap> <select parameterType = "long" id = "getRole" resultMap = "roleResultMap"> select id,role_name,note from t_role where id = #{id} </select>
<insert parameterType = "role" id = "insertRole"> insert into t_role(role_name,note) values (#{roleName},#{note}) </insert>
有时候我们还需要声名主键 ,在声明的时候,我们传入的参数模型是不需要传入id这个属性的,因为我们会另外拿出来声明,使用keyProperty指定哪个是主键字段,用useGeneratedKeys属性告诉MyBatis这个主键是否使用数据库内置策略生成;
<insert id = "insertRole" parameterType = "role" useGeneratedKeys = "true" keyProperty = "id"> insert into t_role (role_name,note) values (#{roleName},#{note}) </insert>
<update parameterType = "role" id = "updateRole"> update t_role set role_name = #{roleName}, note = #{note} where id = #{id} </update> <delete id = "delete" parameterType = "long" delete from t_role where id = #{id} </delete>
<sql id = "role_columns"> id,role_name,note </sql> <select parameterType = "long" id = "getRole" resultMap = "roleMap"> select <include refid = "role_columns"/> from t_note where id = #{id} </select> <select parameterType = "map" id = "findRoles"> select id, role_name,note from t_role where role_name like concat('%',#{roleName},'%') and note like concat('%',#{note,'%'}) </select>