0

这是dao层的代码

@Mapper
public interface UserDao {
    String TABLE_NAME = "user";
    String INSET_FIELDS = " username, password, salt, head_url ";
    String SELECT_FIELDS = " id, username, password, salt, head_url";
    
    @Insert({"insert into ", TABLE_NAME, "(", INSET_FIELDS,
    ") values (#{username},#{password},#{salt},#{headUrl})"})
    int addUser(User user);

    @Select({"select ", SELECT_FIELDS, " from ", TABLE_NAME, " where id=#{id}"})
    User selectById(int id);
    
    @Select({"select ", SELECT_FIELDS, " from ", TABLE_NAME, " where username=#{name}"})
    User selectByName(String name);
    
    @Update({"update ", TABLE_NAME, " set password=#{password} where id=#{id}"})
    void updatePassword(User user);
    
    @Delete({"delete from ", TABLE_NAME, " where id=#{id}"})
    void deleteById(int id);
}

这是model层的代码

public class User {
    private int id;
    private String username;
    private String password;
    private String salt;
    private String headUrl;

    public User() {

    }
    public User(String username) {
        this.username = username;
        this.password = "";
        this.salt = "";
        this.headUrl = "";
    }

    public String getuserName() {
        return username;
    }

    public void setuserName(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getSalt() {
        return salt;
    }

    public void setSalt(String salt) {
        this.salt = salt;
    }

    public String getHeadUrl() {
        return headUrl;
    }

    public void setHeadUrl(String headUrl) {
        this.headUrl = headUrl;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    } 
}

当注入完UserDao后,通过把user数据插入数据库后userDao.addUser(user);数据库有内容,可是如果获取id,user.getId() id永远是0,请问这是为何啊?

1个回答

1

已采纳
<insert id="addUser" parameterType="com.queen.mybatis.bean.User">
    insert into
    t_user(loginId,userName,role,note)
    values(#{loginId},#{userName},#{role},#{note})
</insert>

这种配置方式并不能在完成插入操作后将插入时的主键值存放到保存的对象中。

修改为:

<insert id="addUser" parameterType="com.queen.mybatis.bean.User"
    useGeneratedKeys="true" keyProperty="id">
    insert into
    t_user(loginId,userName,role,note)
    values(#{loginId},#{userName},#{role},#{note})
</insert>

mysql支持自增主键,自增主键值的获取,mybatis也是利用statement.getGenreatedKeys();
useGeneratedKeys=”true”;使用自增主键获取主键值策略
keyProperty;指定对应的主键属性,也就是mybatis获取到主键值以后,将这个值封装给javaBean的哪个属性

参考这里:http://www.marsitman.com/myba...

楼主遇到问题要学会自己google啊,你遇到的问题%80,别人都遇到过。
比如说你在MyBatis得不到主键值。或者主键(Id)得到的为0

撰写答案

Planets