为什么在从 spring-data-jpa 保存返回的实体中未设置 ID [英] Why is ID not set in entity returned from spring-data-jpa save

查看:75
本文介绍了为什么在从 spring-data-jpa 保存返回的实体中未设置 ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a simple entity. I'm using spring-data-jpa version 1.2.0.RELEASE and 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.
}

我想保存它.我的存储库看起来像

I want to save it. My repository looks like

public interface PlatformRepository extends JpaRepository<Platform, Long> {

    Platform findByName( String name );
}

我的控制器用这个方法很简单

My Controller is very simple with this method

@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.表定义为:

Select * from platform shows that Test1 has an ID of 6. The table is defined as:

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

我希望在保存后设置 ID,但事实并非如此.他们不会指望我在写入实体后立即进行查找,对吗?

I expect the ID to be set after the save, but it isn't. They're not expecting me to do a lookup immediately after writing the entity, right?

推荐答案

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

You have not specified that the ID was autogenerated by the database in your mapping. Add

@GeneratedValue(strategy = GenerationType.IDENTITY)

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

to your ID field. Without it, JPA doesn't know that it must execute a select statement after insertion in order to get the generated ID from the database.

这篇关于为什么在从 spring-data-jpa 保存返回的实体中未设置 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆