遇到一个很神奇的 mybatis 问题,各位大佬帮忙看看

31 天前
 NiceGeekJasonChu
遇到一个很神奇的 mybatis 问题,各位大佬帮忙看看
在使用 mybatis 根据主键更新数据的时候,使用 updateByPrimaryKeySelective 方法。更新的实体上打了主键标签(@Id ),主键 id 也不是 null ,但是就更新不了数据。
1867 次点击
所在节点    Java
23 条回复
waterlaw
31 天前
mybatis 什么版本不说一下 😂
NiceGeekJasonChu
31 天前
@waterlaw <dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.13</version>
</dependency>

<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>4.1.5</version>
</dependency>
NiceGeekJasonChu
31 天前
SQL 日志打印出来居然不是根据主键 id 更新:
Preparing: UPDATE admin SET name = ?,password = ?,age = ?,sex = ?,phone = ? WHERE name = ? AND password = ? AND age = ? AND sex = ? AND phone = ?
waterlaw
31 天前
@NiceGeekJasonChu 实体类和 Mapper 看下,tkmybatis 没用过
NiceGeekJasonChu
31 天前
@waterlaw #4
@Table(name = "admin")
public class Admin {

/**
* 主键 id
*/
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;

/**
* 用户名
*/
@Column(name = "name")
private String name;

/**
* 密码
*/
@Column(name = "password")
private String password;
}
waterlaw
31 天前
@NiceGeekJasonChu Mapper 直接使用这个实体类 Admin 吗?还需要配置 Admin 的扫描路径吗
waterlaw
31 天前
我这边更新成功了 ,id 列加下注解 @Column
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "id")
private Integer id;
waterlaw
31 天前
不加 @Column 注解也是更新成功的,mybatis-spring-boot-starter 和 mapper 的版本和你一样
waterlaw
31 天前
create table admin(id int(32) primary key, name varchar(20)); 必须声明主键,否则更新失败。
waterlaw
31 天前
不是主键也更新成功了。create table admin(id int(32), name varchar(20));
RedBeanIce
31 天前
你的注解不是 mybatis 的。
RedBeanIce
31 天前
@RedBeanIce 我错了,,请使用 mybatisplus 吧,tk mapper 不行了。
NiceGeekJasonChu
31 天前
@waterlaw 不加 @Column 注解应该也是可以的,但是我就不行,不知道哪里出了问题
forest997
31 天前
是不是 @Id 用成了别的包的,正确的是 javax.persistence 包的,mapper.xml 的 resultMap 里面有没有配<id>
forest997
31 天前
@forest997 #14 mapper.xml 的 resultMap 里面有没有配“<id>”
forest997
31 天前
@forest997 #15 是 id 标签,怎么老被吞
pangdundun996
31 天前
debug 看看 sql 生成逻辑,这种估计是内部注解处理的问题
NiceGeekJasonChu
31 天前
@forest997 这个我检查过了,是 javax. persistence
NiceGeekJasonChu
31 天前
@pangdundun996 debug 过了,日志也打了,where 条件里面压根就没有 id ,打印日志我上面发过
NiceGeekJasonChu
31 天前
问题找到了,我在主键上加上 @Column(name = "id")注解,就能更新成功。但是我看有的人没有加这个注解,也能更新成功。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/1032454

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX