简体   繁体   中英

Why is ID not set in entity returned from spring-data-jpa save

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;
}

And the response from that method is

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

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);

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?

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

@GeneratedValue(strategy = GenerationType.IDENTITY)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM