【问题标题】:JPA using @SQLInsert throws Parameter index out of range使用 @SQLInsert 的 JPA 抛出参数索引超出范围
【发布时间】:2018-11-15 02:40:25
【问题描述】:
@Data
@MappedSuperclass
public class BaseModel implements Serializable {
 private static final Long serialVersionUID = -1442801573244745790L;

 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 private Long id;

 @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
 @Convert(converter = LocalDateTimeConverter.class)
 private LocalDateTime createAt = LocalDateTime.now();

 @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
 @Convert(converter = LocalDateTimeConverter.class)
 private LocalDateTime updateAt = LocalDateTime.now();
}


@Data
@Entity
@Table(name = "tb_vip_code")
@SQLInsert(sql = "insert ignore into tb_vip_code (code, duration) values (?, ?)")
public class VipCode extends BaseModel {
private static final Long serialVersionUID = -4697221755301869573L;

private String code;
private Integer duration;
private Integer status = 0;
private Long userId;

public VipCode() {}
}

@Test
public void addOne() throws Exception {
    VipCode vipCode = new VipCode();
    vipCode.setCode("123456");
    vipCode.setDuration(1);
    service.addOne(vipCode);
}

create table tb_vip_code
(
id bigint auto_increment
    primary key,
code varchar(20) not null,
status int default '0' not null,
user_id bigint null,
duration int not null,
create_at datetime default CURRENT_TIMESTAMP not null,
update_at timestamp default CURRENT_TIMESTAMP not null,
constraint tb_vip_code_code_uindex unique (code)
);

所有代码如上,我正在尝试使用自定义 sql 来保存对象,但它会引发异常: 原因:java.sql.SQLException: Parameter index out of range (3 > number of parameters, which is 2).

我只有两个参数,为什么说需要三个?

【问题讨论】:

    标签: java sql hibernate spring-data-jpa parameterbinding


    【解决方案1】:

    @SQLInsert 指定的 SQL 语句获取绑定为参数的实体的字段。

    VipCode 实体中至少有 4 个属性,我怀疑它继承自 BaseModel 类的属性更多。但是您的 SQL 语句只需要两个参数。

    要解决此问题,请从实体中删除多余的属性,将它们的参数添加到查询中或将它们标记为@Transient

    【讨论】:

      猜你喜欢
      • 2012-05-04
      • 2014-06-06
      • 1970-01-01
      • 2012-09-20
      • 1970-01-01
      • 2019-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多