Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 372
digitaljoel Avatar asked Dec 16 '12 05:12

digitaljoel


People also ask

What does the Save method return in Spring data JPA?

The save() method returns the saved entity, including the updated id field.

What is difference between save and saveAll in JPA?

In our case, each time we call the save() method, a new transaction is created, whereas when we call saveAll(), only one transaction is created, and it's reused later by save().

What is the difference between save and Saveflush in JPA?

Both methods are used to save entities to the database. Flushing is the process of synchronizing the state of the persistence context with the underlying database. When using saveAndFlush method, data immediately flush to the database and to do it with the save method we need to call flush() method explicitly.

What is entity and ID in Spring Boot?

EntityManager: It is an interface. It controls the persistence operations on objects. It works for the Query instance. Entity: The entities are the persistence objects stores as a record in the database. Persistence Unit: It defines a set of all entity classes.


1 Answers

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.

like image 98
JB Nizet Avatar answered Oct 09 '22 17:10

JB Nizet