使用JPA与MySQL交互。代码
ImpsLogEntity类
@Entity
@Table(name = "imps_log")
@Getter
@Setter
public class ImpsLogEntity extends ImpsLog {}
ImpsLog类
@Setter
@Getter
@JsonIgnoreProperties(ignoreUnknown = true)
@MappedSuperclass
@ToString
public class ImpsLog {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "amount")
private BigDecimal amount;
@Column(name = "created_at")
@CreationTimestamp
private Date createdAt;
@Column(name = "updated_at")
@UpdateTimestamp
private Date updatedAt;
}
ImpsLogRepo
public interface ImpsLogRepo extends JpaRepository<ImpsLogEntity, Long> {
}
ImpsLogBo
@Getter
@Setter
public class ImpsLogBo extends ImpsLog {
private Error error;
}
AccountMapper(使用mapstruct)
@Mapper(componentModel = "spring")
@DecoratedWith(AccountMapperDecorator.class)
public interface AccountMapper {
ImpsLogEntity impsLogBoToImpsLogEntity(final ImpsLogBo impsLogBo);
}
创建和保存对象:
ImpsLogBo impsLogBo = new ImpsLogBo() ;
impsLogBo.setAmount(new Bigdecimal(200));
ImpsLogEntity impsLogEntity =
this.accountMapper.impsLogBoToImpsLogEntity(impsLogBo);
impsLogEntity = this.impsLogRepo.save(impsLogEntity);
imps_log的SQL create语句
CREATE TABLE `imps_log` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`amount` decimal(15,2) DEFAULT NULL,
`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `created_at` (`created_at`),
KEY `updated_at` (`updated_at`)
)
此代码为 org.hibernate.engine.jdbc.spi.SqlExceptionHelper- 保存到数据库时,“ created_at”列不能为空错误。
*
奇怪的部分,对于此注释,其他实体也是如此。而且对于这个实体,这个错误也不是一致的。
*