Home > Blockchain >  Usage @ManyToOne in @EmbeddedId class
Usage @ManyToOne in @EmbeddedId class

Time:09-17

Java Persistence 2.1. Chapter 2.5 says:

An embeddable class may contain a relationship to an entity or collection of entities. Since instances of embeddable classes themselves have no persistent identity, the relationship from the referenced entity is to the entity that contains the embeddable instance(s) and not to the embeddable itself. An embeddable class that is used as an embedded id or as a map key must not contain such a relationship.

I created this relationship and everything works. Please tell me why it is imposssble to do this?

My Embeddable class AuthorizationHistorySssPropertyPK:

@Embeddable
@Data
@NoArgsConstructor
@AllArgsConstructor
public class AuthorizationHistorySssPropertyPK implements Serializable {

    @ManyToOne
    @JoinColumn(name = "applicationSss", referencedColumnName = "sss", nullable = false)
    private Sss sss;

    @Column(name = "dataTime", nullable = false)
    private Timestamp dataTime;

}

My class AuthorizationHistory with @EmbeddedId:

@Entity
@Table(name = "`AuthorizationHistory`")
@Data
@NoArgsConstructor
public class AuthorizationHistory {

    @EmbeddedId
    private AuthorizationHistorySssPropertyPK authorizationHistorySssPropertyPK;

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

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

    @Column(name = "status", nullable = false)
    private byte status;

    public AuthorizationHistory(Sss sss, String login, String password, Timestamp timestamp, byte status) {
        this.authorizationHistorySssPropertyPK = new AuthorizationHistorySssPropertyPK(sss,timestamp);
        this.login = login;
        this.password = password;
        this.status = status;
    }

}

And class Sss:

@Entity
@Table(name = "`SSS`")
@Data
@NoArgsConstructor
public class Sss {

    @Id
    @Column(name = "sss", nullable = false)
    private int sss;

    // ..... 
}

The database was created a long time ago and I can't change it. But table AuthorizationHistory doesn't have field ID. I need to create this table with Hibernate with a composite key or ... don't know. But I have to do it right. Help my please. How to do it correctly?

CodePudding user response:

As it's stated in the hibernate documentation:

Hibernate supports directly modeling @ManyToOne associations in the Primary Key class, whether @EmbeddedId or @IdClass.

However, that is not portably supported by the JPA specification. In JPA terms, one would use "derived identifiers". For more details, see Derived Identifiers.

  • Related