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?
The save() method returns the saved entity, including the updated id field.
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().
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With