Why is the id null in the entity after saveandflush but not null in the database?
<p>I use the latest <strong>Spring Boot</strong> with <strong>Spring Data JPA</strong> and <strong>Hibernate</strong>. The database used is <strong>Oracle 11G</strong>. I've been searching a solution for a couple of days but nothing worked.
I struggle to <strong>retrieve the id</strong> of an entity newly inserted (successfully) in the database. I use a sequence and a trigger. e.g.</p>

<p>The entity:</p>

<pre><code>    @Entity
    public class Address implements Serializable {
    @Id
    @Column(name = "ID", nullable = false, precision = 0)
    @SequenceGenerator(name = "SEQ_ID_GEN", sequenceName = "GI2S1.SEQ_ID", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_ID_GEN")
    private long id;
    private String addressLine;
    private String addressLine2;
    private String city;
    private String postalCode;

    @Id
    public long getId() {
        return id;
    }
    Getters &amp; setters omitted...
</code></pre>

<p>The trigger:</p>

<pre><code>CREATE OR REPLACE TRIGGER SEQ_ADDRESS_TRIG
    BEFORE INSERT ON ADDRESS
    FOR EACH ROW
BEGIN
    SELECT SEQ_ID.nextval
    INTO :new.id
    FROM dual;
END;
/
</code></pre>

<p>The sequence:</p>

<pre><code>CREATE SEQUENCE SEQ_ID START WITH 1 INCREMENT BY 1 MINVALUE 1;
</code></pre>

<p>The query is performed in the controller. e.g.</p>

<pre><code>@Controller
@RequestMapping("/address")
public class AddressController {

@Autowired
private AddressRepository addressRepository;

@Transactional
public Address saveAddress(Address address) {
    try {
        return addressRepository.saveAndFlush(address);
    } catch (Exception ex) {
        System.out.println(ex);
    }
    return null;
}

@PostMapping("/create")
public String create(@ModelAttribute Address address) {
    Address saved = saveAddress(address);
    long id = saved.getId();

    System.out.println(saved);

    return (id &gt; 0) ?
            "redirect:/address/find?id=" + id
            :
            "redirect:/address/list";
}
</code></pre>

<p>The result after a findAll
    {"id":81,"addressLine":"aa","addressLine2":"a","city":"a","postalCode":"a"}</p>

<p>but here is the object after a System.out.println(saved);</p>

<pre><code>Address{id=0, addressLine='aa', addressLine2='a', city='a',
postalCode='a'}
</code></pre>

<p>The repository:</p>

<pre><code>@Transactional
public interface AddressRepository extends JpaRepository&lt;Address, Long&gt; {
    List&lt;Address&gt; findByCity(String city);
}
</code></pre>

<p>I suspect there's a problem with the session, the data isn't just yet committed. Am I right? How to resolve it? Thanks!</p>