javahibernatejpapersist

Autogenerated field of embedded id is null after JPA persisting


I have a class structure made up of a main class (called MaterialResource) that has an embedded id (called MaterialResourceId). Note also that the MaterialResourceId class has two fields: idMaterialResource and idCompany. idMaterialResource is autogenerated with strategy identity.

The problem is that when I persist a MaterialResource object (with idMaterialResource set to null, as it should be auto-generated) the database insertion works perfectly, but the returned object has the idMaterialResource field set to null too. This way I cannot know what id (what number) has been assigned to my newly created object.

The classes are the following. This is the main class:

@Entity
@Table(name = "material_resource")
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class MaterialResource {

    @EmbeddedId
    private MaterialResourceId materialResourceId;

    @Column(name = "name", nullable = false)
    private String name = "";
    ...
}

This is its embedded id:

@Embeddable
@Data
@AllArgsConstructor
@NoArgsConstructor
public class MaterialResourceId implements Serializable {
    private static final long serialVersionUID = 1L;

    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id_materialresource")
    private Integer idMaterialResource;

    @Column(name = "id_company")
    private Integer idCompany;
}

(Note that I'm using the lombok annotations to generate getters, setters, equals, hashCode...)

Now, if I try to execute:

MaterialResourceId id = new MaterialResourceId(null, 1);
MaterialResource materialResource = MaterialResource(id, "Material resource name", ...);
getEntityManager().persist(materialResource);

(Note that all the previous code is placed inside an entity manager transaction)

It turns out that materialResource.materialResourceId.idMaterialResource is null. As I said, this is a problem since I cannot know which id has been assigned. Thus, I cannot return to the client the id of the created object, I cannot find the object in the database...

However, if I inspect the database with an external app (DBeaver), a row in the MaterialResource table has been properly created (with an autogenerated value for idMaterialResource).

The Flyway script for creating the MaterialResource table is the following (here is where I set id_materialresource to be auto-generated).

CREATE TABLE IF NOT EXISTS material_resource(
    id_materialresource INT NOT NULL AUTO_INCREMENT,
    id_company INT NOT NULL,
    name VARCHAR(255) NOT NULL DEFAULT "",
    identifier VARCHAR(255) NOT NULL DEFAULT "",
    fromDate DATE NOT NULL,
    toDate DATE NOT NULL,
    PRIMARY KEY (id_recurso, id_empresa)
);

Any help is useful. Thanks!


Solution

  • Actually, I have found the answer to my question here. Basically, auto-generated composed ids are currently not supported in Hibernate.