2012-12-16 106 views
9

我有一個簡單的實體。我使用的是spring-data-jpa版本1.2.0.RELEASE和eclipselink 2.4.1。爲什麼從spring-data-jpa返回的實體中沒有設置ID save

@Entity 
@Table(name="platform") 
public class Platform { 

    @Id 
    @Column(name="id", nullable=false, updatable=false, insertable=true) 
    private Long id; 
    // etc. 
} 

我想保存它。我的庫看起來像是

public interface PlatformRepository extends JpaRepository<Platform, Long> { 

    Platform findByName(String name); 
} 

我的控制器是非常簡單的用這種方法

@RequestMapping(method=RequestMethod.POST, produces="application/json") 
public Platform post(Platform platform) { 
    Platform result = platformDao.saveAndFlush(platform); 
    return result; 
} 

,並從該方法的響應是

{"platform":{"id":null,"name":"Test1"}} 

SELECT * FROM平臺顯示的Test1有一個ID 6.該表定義爲:

create table platform(
id int not null auto_increment primary key, 
name varchar(128) not null); 

我希望在保存後設置ID,但事實並非如此。他們不希望我在寫完實體後立即查找,對吧?

+0

只是一個猜測:嘗試將ID從'Long'更改爲'int',將'insertable = true'更改爲'false'。此外,[*這*](http://stackoverflow.com/questions/12122489/jparepository-transaction-and-repository-saveandflush)可能是相關的。 – alfasin

回答

13

您尚未指定該ID由映射中的數據庫自動生成。將

@GeneratedValue(strategy = GenerationType.IDENTITY) 

添加到您的ID字段。沒有它,JPA不知道它必須在插入後執行select語句才能從數據庫中獲取生成的ID。

+0

杜......我知道。一旦我確認,我會盡快接受。 – digitaljoel

相關問題