Java – JPA many to many connection table entity, compound key “null ID generated”

This is my entity:

public class Account extends AbstractEntity<Long> {

    @Id
    @SequenceGenerator(name = "accountSequence",sequenceName = "SQ_ACCOUNTS",allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "accountSequence")
    @Column(name = "ACC_ID",nullable = false)
    private Long id;
...
}

public class Integration extends AbstractEntity<Long> {

    @Id
    @SequenceGenerator(name = "integrationSequence",sequenceName="SQ_INTEGRATIONS",generator = "integrationSequence")
    @Column(name = "INT_ID",nullable = false)
    private Long id;
...
public void addIntegration(Integration integration) {
        IntegrationAccount association = new IntegrationAccount();
            // This does not help
        //association.setIntAccountsPK(new IntAccountsPK(integration.getId(),this.getId()));
        association.setAccount(this);
        association.setIntegration(integration);
        this.integrationAccounts.add(association);
        integration.getIntAccountsCollection().add(association);
    }
}

This is the entity that joins the table

@Entity
@Table(name = "INT_ACCOUNTS")
public class IntegrationAccount  {

    @EmbeddedId
    protected IntAccountsPK intAccountsPK;

    @JoinColumn(name = "ACC_ID",referencedColumnName = "ACC_ID",insertable = false,updatable = false)
    @ManyToOne
    private Account account;

    @JoinColumn(name = "INT_ID",referencedColumnName = "INT_ID",updatable = false)
    @ManyToOne
    private Integration integration;
...
}
@Embeddable
public class IntAccountsPK  implements Serializable {

    @Column(name = "INT_ID",nullable = false)
    private Long intId;

    @Column(name = "ACC_ID",nullable = false)
    private Long accId;
...
}

When I do this:

account.addIntegrations(integrations.getTarget());
account.setCustomer(customer);
accountService.save(account);

I got this in my blog: org hibernate. Id.identifiergenerationexception: null ID generated for: class com dhl. dcc. domain. IntegrationAccount

I don't know much about this mapping. Please tell me how to improve this mapping (the entities of the connection table must be retained) and how to use relevant integration to save accounts? thank you.

Solution

You can create an ID field for the integration account, and then create a unique constraint for the two fields

@Entity
@Table(name = "INT_ACCOUNTS",uniqueConstraints=@UniqueConstraint(columnNames={"ACC_ID","INT_ID"}))
public class IntegrationAccount  {

    @Id
    private Long id;

    @JoinColumn(name = "ACC_ID",updatable = false)
    @ManyToOne
    private Integration integration;
...
}

Miraculously effective!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>