当数据库字段与实体类字段不相同时的解决方法
程序员文章站
2024-02-11 14:06:31
...
1.数据库
2.实体类(字段名不同)
package cn.yf.entity;
public class Admin {
private int admin_id;
private String admin_name;
private String admin_password;
public Admin() {
}
public Admin(int admin_id, String admin_name, String admin_password) {
this.admin_id = admin_id;
this.admin_name = admin_name;
this.admin_password = admin_password;
}
public Admin(String admin_name, String admin_password) {
this.admin_id = admin_id;
this.admin_name = admin_name;
this.admin_password = admin_password;
}
public int getAdmin_id() {
return admin_id;
}
public void setAdmin_id(int admin_id) {
this.admin_id = admin_id;
}
public String getAdmin_name() {
return admin_name;
}
public void setAdmin_name(String admin_name) {
this.admin_name = admin_name;
}
public String getAdmin_password() {
return admin_password;
}
public void setAdmin_password(String admin_password) {
this.admin_password = admin_password;
}
@Override
public String toString() {
return "Admin{" +
"admin_id=" + admin_id +
", admin_name='" + admin_name + '\'' +
", admin_password='" + admin_password + '\'' +
'}';
}
}
3.使用ResultMap解决
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.yf.mapper.AdminMapper">
<!--column:数据库字段-->
<!--property:实体类字段-->
<resultMap id="adminResultMap" type="cn.yf.entity.Admin">
<id property="admin_id" column="id" ></id>
<result property="admin_name" column="name"></result>
<result property="admin_password" column="password"></result>
</resultMap>
<select id="queryAdminById" resultType="Admin" parameterType="int" resultMap="adminResultMap">
select * from admin where id = #{admin_id}
</select>
<insert id="addAdmin" parameterType="Admin" >
insert into admin(name,password) values(#{admin_name},#{admin_password})
</insert>
<delete id="deleteAdmin" parameterType="int">
delete from admin where id = #{admin_id}
</delete>
<update id="updateAdmin" parameterType="Admin">
update admin set name=#{admin_name},password=#{admin_password} where id=#{admin_id}
</update>
<select id="queryAllAdmin" resultType="Admin" resultMap="adminResultMap">
select * from admin
</select>
</mapper>
<resultMap id="adminResultMap" type="cn.yf.entity.Admin">
<id property="admin_id" column="id" ></id>
<result property="admin_name" column="name"></result>
<result property="admin_password" column="password"></result>
</resultMap>
上一篇: android 模拟器介绍