Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA define relationship on a field that requires type conversion

I want to join two tables on column "vendor", In invoice table vendor type is integer, in vendor table, vendor is type varchar(10).

Is it possible to do a type conversion and also have a relationship?

@Entity
public class Vendor
{
    private String id;

    @Id(Column="vendor")
    public String getId(){ ... }
}

@Entity
public class Invoice
{
    private Vendor vendor;

    @One-to-one
    public Vendor getVendor() { ... }
}
like image 793
Frank Avatar asked Nov 15 '22 05:11

Frank


1 Answers

As far as I know, using a pivot table (as you would do to represent a many-to-many relationship) would be the right way to do that.

Something like this should work:

@Entity
public class Invoice
{
    @JoinTable(name = "invoice_vendor", joinColumns = {
        @JoinColumn(name = "invoice", referencedColumnName = "vendor_id")}, inverseJoinColumns = {
        @JoinColumn(name = "vendor", referencedColumnName = "id")})
    @OneToOne
    private Vendor vendor;
}

Where the invoice_vendor table has the integer id in id column and varchar reference in vendor_id column.

Also I surmise you would like a ManyToOne relationship between vendors, but you've written one to one, so I have left that as such.

like image 58
mcyalcin Avatar answered Dec 10 '22 07:12

mcyalcin