Ivan Ivan - 12 days ago 6
Java Question

Why is the id null in the entity after saveandflush but not null in the database?

I use the latest Spring-boot with data-jpa and Hibernate. The database used is Oracle 11G. I've been searching a solution for a couple of days but nothing worked.
I struggle to retrieve the id of an entity newly inserted (successfully) in the database. I use a sequence and a trigger. e.g.

The entity:

@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 & setters omitted...


The trigger:

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


The sequence:

CREATE SEQUENCE SEQ_ID START WITH 1 INCREMENT BY 1 MINVALUE 1;


The query is performed in the controller. e.g.

@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 > 0) ?
"redirect:/address/find?id=" + id
:
"redirect:/address/list";
}


The result after a findAll


{"id":81,"addressLine":"aa","addressLine2":"a","city":"a","postalCode":"a"}


but here is the object after a System.out.println(saved);


Address{id=0, addressLine='aa', addressLine2='a', city='a',
postalCode='a'}


The repository:

@Transactional
public interface AddressRepository extends JpaRepository<Address, Long> {
List<Address> findByCity(String city);
}


I suspect there's a problem of session, the data isn't just yet commited. Am 'I right? How to resolve it? Thanks!

Answer

Problem solved!

There was an @Id annotation before the getter getId in the address entity.

Just removed the annotation

Before:

@Id
public long getId() {
    return id;
}

After:

public long getId() {
    return id;
}