【问题标题】:Why is ID not set in entity returned from spring-data-jpa save为什么从spring-data-jpa保存返回的实体中没有设置ID
【发布时间】:2012-12-16 05:47:44
【问题描述】:

我有一个简单的实体。我正在使用 spring-data-jpa 版本 1.2.0.RELEASE 和 eclipselink 2.4.1。

@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 platform 显示Test1的ID为6,表定义为:

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

我希望在保存后设置 ID,但事实并非如此。他们不希望我在编写实体后立即进行查找,对吧?

【问题讨论】:

  • 只是猜测:尝试将 idLong 更改为 intinsertable=true 更改为 false。此外,this 可能是相关的。

标签: java spring-data spring-data-jpa


【解决方案1】:

您尚未指定 ID 是由映射中的数据库自动生成的。添加

@GeneratedValue(strategy = GenerationType.IDENTITY)

到您的 ID 字段。没有它,JPA 不知道它必须在插入后执行 select 语句才能从数据库中获取生成的 ID。

【讨论】:

  • 呃……我知道。我会在验证后立即接受。
  • 我面临同样的问题,但即使在使用 @GeneratedValue(strategy = GenerationType.IDENTITY) 之后问题仍然存在。还有其他解决方法吗?
猜你喜欢
  • 2023-01-27
  • 2020-03-26
  • 2019-09-30
  • 2013-05-09
  • 2018-07-31
  • 2021-10-16
  • 1970-01-01
  • 2016-10-11
  • 1970-01-01
相关资源
最近更新 更多