'Mapping two columns in JPA

I have the following 3 tables

table: project
id
company_code
number
contract_type_code
account_type_code
other columns…

table: contract_type
id
company_code
code
name

table: account_type
id
company_code
code
name

The project table references contract_type and account_type tables through contract_type_code/company_code and account_type_code/company_code respectively.

The company_code and code columns are what make a contract_type and account_type unique.

I'm struggling with modelling and mapping this in JPA. I've tried with the @JoinColumn and @JoinColumns annotation and there's no way for me to make it work.

This is one of the ways I've been trying with no success:

public class Project implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private Long companyCode;

    private Long number;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumns({
            @JoinColumn(name = "contract_type_code", referencedColumnName = "code"),
            @JoinColumn(name = "company_code", referencedColumnName = "company_code")
    })
    private ContractType contractType;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumns({
            @JoinColumn(name = "account_type_code", referencedColumnName = "code"),
            @JoinColumn(name = "company_code", referencedColumnName = "company_code")
    })
    private AccountType accountType;

This is the issue I'm getting with the mapping above:

Caused by: org.hibernate.MappingException: Unable to find column with logical name company_code in table contract_type

For this mapping:

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumns({
        @JoinColumn(name = "contract_type_code", referencedColumnName = "code", insertable = false, updatable = false),
        @JoinColumn(name = "company_code", referencedColumnName = "company_code2", insertable = false, updatable = false)
})
private ContractType contractType;

I get:

Caused by: org.hibernate.DuplicateMappingException: Table [account] contains physical column name [company_code] referred to by multiple logical column names: [company_code], [companyCode]


Solution 1:[1]

I assume you have companyCode fields in the AccountType and ContractType. Annotate them as below (first error suggests JPA can't find them):

@Column(name = "company_code")

In your Project class modify companyCode field as follows (to avoid the second error):

@Column(name = "company")
private Long companyCode;

and keep mapping with:

insertable = false, updatable = false

Hope this will help. If not please add AccountType and ContractType classes to your question. Maybe then it will be easier to sort it out

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mpdgr