我正在開發一項服務,目前正在處理它的 2 個物體 (Section和GradeLevel) 當我仍在開發時,我決定使用 H2 并從 Java 代碼生成表。
節.java
@Entity
@Setter
@Getter
public class Section{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(unique = true, nullable = false)
private String name;
@OneToOne
private GradeLevel gradeLevel;
@Column(columnDefinition = "boolean default TRUE")
private boolean isActive;
@Column(columnDefinition="TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
private Timestamp dateCreated;
private Timestamp dateLastUpdated;
}
GradeLevel.java
@Entity
@Getter
@Setter
public class GradeLevel {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(unique = true, nullable = false)
private String code; //GL-01, GL-02...
@Column(unique = true)
private String description; //Kinder 1, Kinder 2, Grade 1....
private String category; //Elementary School, Junior Highschool, Senior Highschool
@Column(columnDefinition = "boolean default TRUE")
private boolean isActive;
@Column(columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
private Timestamp dateCreated;
private Timestamp dateLastUpdated;
}
SectionRESTController.java
@RestController
@RequestMapping(value = "/api/sections")
public class SectionRESTController {
@Autowired
private SectionService sectionService;
@GetMapping(path = "/{sectionId}")
public Section getSectionById(@PathVariable("sectionId") Long id) {
return sectionService.getSectionById(id);
}
@PostMapping(consumes = "application/json", produces = "application/json")
public ResponseEntity<Section> createSection(@Valid @RequestBody SectionCreateDTO sectionCreateDTO) {
Section createdSection = sectionService.createSection(sectionCreateDTO.toSection());
if (createdSection == null) {
return ResponseEntity.notFound().build();
} else {
URI uri = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{sectionId}")
.buildAndExpand(createdSection.getId())
.toUri();
return ResponseEntity.created(uri)
.body(createdSection);
}
}
}
SectionCreateDTO.java
@Data
public class SectionCreateDTO {
@NotEmpty(message = "Section name is required.")
private String name;
@NotNull(message = "gradelevel id is required.")
private Long gradeLevelId;
public Section toSection() {
Section section = new Section();
section.setName(name);
GradeLevel gradeLevel = new GradeLevel();
gradeLevel.setId(gradeLevelId);
section.setGradeLevel(gradeLevel);
return section;
}
}
問題:
控制器createSection()方法沒有插入部分和列的DEFAULT列值 。我已將這兩列都設定為具有和默認值IS_ACTIVEDATE_CREATEDTRUECURRENT_TIMESTAMP
Postman 中的示例請求:
POST localhost:8080/api/sections
{
"name": "MERCURY",
"gradeLevelId" : 1
}
在 H2 控制臺中,Section表格顯示NULL了FALSE這些欄位。而不是正確的時間戳和 TRUE 值。

應用程式屬性
#========================================================================
#H2 Properties
#========================================================================
spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=update
我不知道這個問題是否僅針對 H2,或者我在這里遺漏了一些東西。
我會很感激任何評論。
====== 編輯。以下是解決方案=======
對我有用的解決方案是:
@Column(columnDefinition = "boolean default true")
private Boolean isActive = true;
@CreationTimestamp
@Column(name = "date_created")
private LocalDateTime dateCreated = LocalDateTime.now();
@UpdateTimestamp
@Column(name = "date_last_updated")
private LocalDateTime dateLastUpdated = LocalDateTime.now();
感謝您的建議和回答。
uj5u.com熱心網友回復:
即使您將布林值更改為布林值,它也不起作用。
Hibernate 總是發送包括空值在內的所有欄位,例如:
INSERT INTO SECTION(..., IS_ACTIVE, ...) VALUES (..., null, ...)
您的資料庫會將 NULL 插入 IS_ACTIVE,而不是默認值。
如果您希望默認為true,請在 Java 中進行設定:
private Boolean isActive = true;
uj5u.com熱心網友回復:
您使用布林值的 IS_ACTIVE 列的問題(默認情況下為 false,但您需要 null)而不是布林值。對于創建的時間戳,您可以嘗試添加 @CreationTimestamp
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/428675.html
上一篇:Spring事務中的LazyInitializationException
下一篇:HibernateSearch:在ElasticSearch上映射IndexedEmbedded導致在映射中找不到[]的欄位
