@Data @AllArgsConstructor @NoArgsConstructor @Builder @Table(name = "advert") public class Advert { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @ApiModelProperty(value = "广告唯一id") private Integer id; @ApiModelProperty(value = "广告名称") @NotBlank(message = "广告名称不可为空", groups = {AddGroup.class, UpdateGroup.class}) private String name; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "position_id") private AdPosition position; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "media_id") private MediaFile media; } @Data @AllArgsConstructor @NoArgsConstructor @Builder @Table(name = "ad_position") public class AdPosition { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @ApiModelProperty(value = "位置名称") @NotBlank(message = "位置名称不可为空", groups = {AddGroup.class}) private String name; @OneToMany(mappedBy = "AdPosition", cascade = CascadeType.ALL) private List<Advert> adverts = new ArrayList<>(); } @Data @AllArgsConstructor @NoArgsConstructor @Builder @Table(name = "media_file") public class MediaFile { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @ApiModelProperty(value = "媒体文件名称") private String fileName; @ApiModelProperty(value = "媒体文件类型") private Integer fileType; @ApiModelProperty(value = "媒体文件URL地址") private String fileUrl; @OneToMany(mappedBy = "MediaFile", cascade = CascadeType.ALL) private List<Advert> adverts = new ArrayList<>(); } public interface MyBaseMapper<T> extends Mapper<T>, MySqlMapper<T>,MyInsertListMapper<T> {} public interface AdvertMapper extends MyBaseMapper<Advert> {} @Autowired private AdvertMapper advertMapper; AdPosition adPosition = Optional.ofNullable(adPositionMapper.selectByPrimaryKey(advertDto.getPositionId())) .orElseThrow(() -> new RuntimeException("Ad position not found")); // 创建一个新的Advert对象 Advert advert = Advert.builder() .name("广告名称") .position(adPosition) // 假设AdPosition表中id为1的记录是需要的位置 .media(new MediaFile(1)) // 假设MediaFile表中id为1的记录是需要的媒体文件 .build(); // 调用insertSelective方法插入数据 advertMapper.insertSelective(advert);,报错Field 'position_id' doesn't have a default value ; Field 'position_id' doesn't have a default value; nested exception is java.sql.SQLException: Field 'position_id' doesn't have a default value,为什么
时间: 2024-04-28 14:23:07 浏览: 102
淘特Asp.NetCms二次开发说明
这个错误是由于在Advert表中的position_id字段没有设置默认值且未被赋值,在执行插入操作时,MySQL会抛出该异常。解决方法是在Advert表中的position_id字段上加上默认值或者在插入操作中给该字段赋值。例如在Advert实体类中的position字段上加上@JoinColumn注解的nullable属性,将它设置为true,表示该字段可以为null。或者在插入操作中给position_id字段赋值,例如advert.setPosition(adPosition)。
阅读全文