javahibernatejpamappedby

JPA Mapping @EmbeddedId with ManyToOne relationship


so I searched for the answers for my problem on the internet but didn't find something that helped, basically a need to have a ManyToOne Relationship between two classes, of which one of them has an EmbeddedId, I'm going to leave the code here and the error message that it gives (I'm using wildfly to run the server).

public class InventoryPK implements Serializable {

    @ManyToMany(cascade = CascadeType.ALL)
    @JoinColumn(name = "user_id")
    private Item itemId;

    @ManyToOne
    @JoinColumn(name="CD_EMPRESA")
    private Company company;
}

@Entity
@Table(name = "inventario", schema = "mxnextmob")

public class Inventory extends BaseModel {

    @EmbeddedId
    private InventoryPK id;

    @SequenceGenerator(schema = "mxnextmob", name = "inventory_sequence", sequenceName = "inventory_sequence", allocationSize = 1, initialValue = 1)
    @GeneratedValue(strategy = GenerationType.AUTO, generator = "inventory_sequence")
    private Integer inventory;

    @Column
    private BigDecimal quantity;

    @Column
    private BigDecimal weight;
}

public class Company extends BaseModel {

    @Id
    @SequenceGenerator(schema = "mxnextmob", name = "company_sequence", sequenceName = "company_sequence", allocationSize = 1, initialValue = 1)
    @GeneratedValue(strategy = GenerationType.AUTO, generator = "company_sequence")
    private Integer code;

    @Column
    private String name;

    @OneToMany(mappedBy = "company")
    private List<UserSeller> userSeller;

    @OneToMany(mappedBy = "id.company")
    private List<Inventory> inventories;
}

and the error is as follows:

service jboss.persistenceunit."mxnext-mobile.war#mxnextmobileDS": org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: br.com.maxiconsystems.mobile.model.Inventory.company in br.com.maxiconsystems.mobile.model.Company.inventory


Solution

  • There are a few ways to map what you seem to have as a table, but I'd recommend Inventory be changed to something like:

    public class Inventory extends BaseModel {
      @Id
      @SequenceGenerator(schema = "mxnextmob", name = "inventory_sequence", sequenceName = "inventory_sequence", allocationSize = 1, initialValue = 1)
      @GeneratedValue(strategy = GenerationType.AUTO, generator = "inventory_sequence")
      private Integer inventory;
    
      @Embedded
      private InventoryPK alternateKey;
    
      @Column
      private BigDecimal quantity;
    
      @Column
      private BigDecimal weight;
    }
    

    This allows you to use the inventory Integer as its primary key; this simplifies any future references you may need to add to Inventory, as foreign keys would be required in JPA to reference all its ID columns.