vladmihalcea / hypersistence-optimizer

Hypersistence Optimizer allows you to get the most out of JPA and Hibernate. By scanning your application configuration and mappings, Hypersistence Optimizer can tell you what changes you need to do to speed up your data access layer.
https://vladmihalcea.com/hypersistence-optimizer/
Apache License 2.0
318 stars 43 forks source link

Unexplainable OneToOneWithoutMapsIdEvent with unidirectional one-to-one #178

Closed pkernevez closed 2 years ago

pkernevez commented 2 years ago

I have the following message, I can't understand: CRITICAL - OneToOneWithoutMapsIdEvent - The [fees] one-to-one association in the [InstrumentEntity] entity is using a separate Foreign Key to reference the parent record. Consider using @MapsId so that the identifier is shared with the parent row. For more info about this event, check out this User Guide link - https://vladmihalcea.com/hypersistence-optimizer/docs/user-guide/#OneToOneWithoutMapsIdEvent

I try to have a unidirectional one-to-one, and maps the parent ID as the child PK. This is my configuration:

@Entity
@Table(name = "INSTRUMENT")
public class InstrumentEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_INSTRUMENT")
    @SequenceGenerator(name = "SEQ_INSTRUMENT", sequenceName = "SEQ_INSTRUMENT", allocationSize = 1)
    private Long id;

    @OneToOne(fetch = FetchType.LAZY, orphanRemoval = true, cascade = CascadeType.ALL)
    @SuppressWarnings({"java:S1948", "Serializable because of CurrencyEntity"})
    @JoinColumn(name = "INSTRUMENT_FEE_ID")
    @MapsId("ID")
    private InstrumentFeeEntity fees;

}

And

@Entity
@Table(name = "INSTRUMENT_FEE")
public class InstrumentFeeEntity {

    @Id
    private Long id;
}

Should I miss something or is it a false positive error ?

vladmihalcea commented 2 years ago

Try using @MapsId not @MapsId("ID").

Also, create an integration test and activate the hbm2ddl tool to let Hibernate create the schema for you. If Hibernate creates a separate FK, then the mapping was not working properly.

vladmihalcea commented 2 years ago

@pkernevez I also tested the @MapsId("ID") mapping, and it's not taken into consideration by Hibernate, falling back to a separate FK.

The fact that Optimizer caught the issue is great because it shows it works. Just try it with @MapsId and see for yourself.