Archimedes Trajano
Archimedes Trajano

Reputation: 41580

Composite keys using IdClass on Hibernate for composite keys when using DataJpaTest

I have JPA class like this

@Data
@Entity
@Table(name = "oss_org_discount")
@IdClass(OrganizationDiscountPK.class)
public class OrganizationDiscount {
    @Id
    @OneToOne(fetch = FetchType.LAZY)
    @EqualsAndHashCode.Exclude
    @JoinColumn(name = "Org")
    @ToString.Exclude
    private Organization organization;

    @EqualsAndHashCode.Include
    @ToString.Include
    private String getOrganizationId() {

        return organization.getId();
    }

    @Id
    @Column(name = "Discount")
    private String discountId;

    private String active;

    @Contract(pure = true)
    public boolean isActive() {

        return "Y".equals(active);
    }

    public void setActive(final boolean active) {

        this.active = active ? "Y":"";
    }
}

And a IdClass.

@Data
public class OrganizationDiscountPK implements Serializable {
    private Organization organization;
    private String discountId;
}

When I view the logs I see the following generated.

Hibernate: alter table oss_org_discount add constraint UK_ecc64ehkc31t6kf0hcdwj1tvi unique (org)

My question is, shouldn't it show something like

Hibernate: alter table oss_org_discount add constraint UK_ecc64ehkc31t6kf0hcdwj1tvi unique (org, discount)

Not sure if it is an error in my part or a bug in Hibernate.

I do see this though...

Hibernate: create table oss_org_discount (discount varchar(255) not null, active varchar(255), org varchar(255) not null, primary key (discount, org))

So another question would be why would a unique constraint be created?

Upvotes: 0

Views: 99

Answers (1)

Archimedes Trajano
Archimedes Trajano

Reputation: 41580

The issue was the OneToOne on the Organization. It should be @ManyToOne

Upvotes: 0

Related Questions