使用@SQLInsert的JPA抛出参数索引超出范围

时间:2018-11-15 02:40:26

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

@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:参数索引超出范围(3>参数数量,即2)。

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

1 个答案:

答案 0 :(得分:0)

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

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

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