2017-05-28 70 views
0

我在同一個項目中有幾個類,其中id始終是自動生成的。但是在這個特定的情況下,我的id值始終爲空。我真的很想知道什麼是錯誤的,因爲經過一些改變後,它停止工作。並將其與其他類進行比較,代碼似乎是相同的。Java JPA GenerationType.Auto值始終爲空

package com.checkin.model.entity; 
import javax.persistence.*; 


@Entity 
public class Checkin { 

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

@Column(nullable = false) 
private String date; 

public Checkin(){ 

} 

public Checkin(String date){ 
    this.date = date; 
    System.out.println(this.id); 
    System.out.println(this.getId()); 
} 


public Long getId() {return id;} 

public void setId(Long id) {this.id = id;} 

public String getDate() {return date;} 

public void setDate(String date) {this.date = date;} 

} 

這就是對象保存在存儲庫:

package com.checkin.model.repository; 

import com.checkin.model.entity.Checkin; 
import org.springframework.data.repository.CrudRepository; 
import org.springframework.stereotype.Repository; 

@Repository("checkinRepository") 
public interface CheckinRepository extends CrudRepository<Checkin, Long> { 
    Checkin findById(Long id); 


} 

終於這是我從郵遞員

得到的結果

enter image description here

+0

什麼底層的數據庫?並顯示id列的DDL定義 –

+0

我並不清楚DDL定義的含義。我使用Hibernate和JPA。關於你關於底層數據庫的問題,下面是我在build.gradle中使用的東西:compile(「org.springframework.boot:spring-boot-starter-data-jpa」) compile(「com.h2database:h2 「) –

+0

@AntonioDelaTorre安裝Hibernate重新創建數據庫表(並丟失信息)並啓用SQL日誌。您將在日誌中具有「DDL」(SQL CREATE TABLE語句)。其他生成DDL的方法:https://geowarin.github.io/generate-ddl-with-hibernate.html。這有點複雜。 –

回答

0

的代型AUTO套底層數據庫生成ID http://docs.oracle.com/javaee/6/api/javax/persistence/GenerationType.html#AUTO

在這種情況下,您要檢查的是H2數據庫id列是否具有生成ID的屬性。我猜測它沒有。我不用自己太多的自己,所以我假設如果你的汽車適用於其他Entities然後那些設置正確。

您可能需要執行下列操作之一:在H2

    • 遷移這裏
    • 更新列重新創建表
  • +0

    感謝您的回答!我正在學習這個教程:https://spring.io/guides/gs/accessing-data-jpa/但我認爲這個問題不是h2或者來自JPA的問題。因爲,當我創建和對象,並將其保存到在Application.java中規定的方式,在數據庫,通過使用:公共CommandLineRunner演示(CheckinRepository庫){ \t \t回報(參數) - > { \t \t \t //保存幾個客戶 \t \t \t repository.save(new Checkin(「Jack」));我得到:2017-05-29 16:50:09.035 INFO 33570 --- [main] com.checkin.Application:Checkin:[id = 1,Date ='Jack'] –

    +0

    所以我認爲它與RESTful界面 –

    +0

    非常感謝!我解決了這個問題......這是你可以想象的最愚蠢的事情之一......我評論了數據庫中的.save,當然如果數據庫沒有收到對象,它不會生成一個ID ... –