我有一个简单的实体。我正在使用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 );
}
我的 Controller 通过这种方法非常简单
@RequestMapping(method=RequestMethod.POST, produces="application/json")
public Platform post( Platform platform ) {
Platform result = platformDao.saveAndFlush(platform);
return result;
}
该方法的响应是
{"platform":{"id":null,"name":"Test1"}}
从平台选择*显示Test1的ID为6。该表定义为:
create table platform(
id int not null auto_increment primary key,
name varchar(128) not null);
我希望ID在保存后设置,但事实并非如此。他们不希望我在写完实体后立即进行查找,对吗?
最佳答案
您尚未指定ID由映射中的数据库自动生成。添加
@GeneratedValue(strategy = GenerationType.IDENTITY)
到您的ID字段。没有它,JPA不知道它必须在插入后执行select语句才能从数据库中获取生成的ID。
关于java - 为什么未在从spring-data-jpa保存返回的实体中设置ID,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13898982/