I'm new in Spring Boot JPA
I have questions in JPA Entity mappings.
there is 4 tables in my MySql DB
SPACE, PROJECT, ISSUE, MEMBER
SPACE is Big Project which contains multiple PROJECT.
PROJECT contains multiple ISSUE.
and MEMBER can join only 1 SPACE and multiple PROJECT which MEMBER belongs to SPACE.
MEMBER can write multiple ISSUE
in this situation, my ERD model is correct?
my ERD
and please check my jpa mappings.
If there's anything wrong, please point it out.
SPACE
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "space_no")
private Long spaceNo;
#NotEmpty
#Column(name = "space_name", unique=true, length = 100)
private String spaceName;
/** 1:N relation */
#OneToMany(mappedBy = "smsSpace")
private List<PmsProject> pmsProjects = new ArrayList<>();
PROJECT
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "project_no")
private Long projectNo;
#Column(name ="space_no")
private Long spaceNo;
#Column(name = "project_name", length = 100)
private String projectName;
/** 1:N relation */
#OneToMany(mappedBy = "pmsProject")
private List<ImsIssue> imsIssues = new ArrayList<>();
#OneToMany(mappedBy = "pmsProject")
private List<PmsProjectMember> projectMembers = new ArrayList<>();
/** N:1 relation */
#ManyToOne
#JoinColumn(name = "space_no", referencedColumnName = "space_no", insertable = false, updatable = false)
private SmsSpace smsSpace;
MEMBER
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "member_no")
private Long memberNo;
#Column(name = "mail_address", unique=true, length = 100)
private String mailAddress;
#Column(name = "name", length = 100)
private String name;
#Column(name = "keyword", length = 1000)
private String keyword;
#Column(name = "image", length = 1000)
private String image;
#Column(name = "password", length = 1000)
private String password;
#Column(name = "user_id", length = 50)
private String userId;
#Enumerated(EnumType.STRING)
private MemberRole role;
public void encodingPassword(String password) {
this.password = password;
}
/** 1:N realtion */
#OneToMany(mappedBy = "mmsMember")
private List<PmsProjectMember> projectMembers = new ArrayList<>();
ISSUE
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "issue_no")
private Long issueNo;
#Column(name ="project_no")
private Long projectNo;
#Column(name = "issue_name", length = 1000)
private String issueName;
#Column(name = "priority")
private Long priority;
#Column(name = "status", length = 20)
private String status;
#Column(name = "summary", length = 100)
private String summary;
#Column(name = "is_overdue")
private Long isOverdue;
#Column(name = "issue_type_cd")
private String issueTypeCd;
/** N:1 relation */
#ManyToOne
#JoinColumn(name = "project_no", referencedColumnName = "project_no", insertable = false, updatable = false)
private PmsProject pmsProject;
PROJECTMEMBER
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "group_no")
private Long groupNo;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "member_no")
private MmsMember mmsMember;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "project_no")
private PmsProject pmsProject;
I've been thinking about it for days, but I can't solve it because I lack knowledge. Please help me.
Assuming I got your situation right, you have A member that can have one Space and multiple project, space has multiple projects, every project can have more than one issue, every member can write more then one issue for each project.
Due to the suggestion the ERD you posted it's not corrected.
Here is the correct ERD
(I just wrote the Foreign Keys and Primary Keys, the rest its up to you)
And here you have all the entites:
Member
#Entity
#Table(name = "MEMBERS")
public class Member {
//members is the property name in Project entity.
#ManyToMany(mappedBy = "members")
Set<Project> projects;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY, generator = "native")
#Column(name = "MEMBER_ID")
private Long id;
#ManyToOne
#JoinColumn(name = "SPACE_ID")
private Space space;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Space getSpace() {
return space;
}
public void setSpace(Space space) {
this.space = space;
}
public Set<Project> getProjects() {
return projects;
}
public void setProjects(Set<Project> projects) {
this.projects = projects;
}
}
Space
#Entity
#Table(name = "SPACES")
public class Space {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY, generator = "native")
#Column(name = "SPACE_ID")
private Long id;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
Issue
#Entity
#Table(name = "ISSUES")
public class Issue {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY, generator = "native")
#Column(name = "ISSUE_ID")
private Long id;
#ManyToOne
#JoinColumn(name = "MEMBER_ID")
private Member member;
#ManyToOne
#JoinColumn(name = "PROJECt_ID")
private Project project;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Member getMember() {
return member;
}
public void setMember(Member member) {
this.member = member;
}
public Project getProject() {
return project;
}
public void setProject(Project project) {
this.project = project;
}
}
Project
#Entity
#Table(name = "PROJECTS")
public class Project {
#ManyToMany
#JoinTable(
name = "PROJECTS_MEMBERS",
joinColumns = #JoinColumn(name = "PROJECT_ID"),
inverseJoinColumns = #JoinColumn(name = "MEMBER_ID"))//Is referring to the id of the other Entity, in this case, members
Set<Member> members;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY, generator = "native")
#Column(name = "PROJECT_ID")
private Long id;
#ManyToOne
#JoinColumn(name = "SPACE_ID")
private Space space;
public Set<Member> getMembers() {
return members;
}
public void setMembers(Set<Member> members) {
this.members = members;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Space getSpace() {
return space;
}
public void setSpace(Space space) {
this.space = space;
}
}
You don't have to put necessarily both #ManyToOne and #OneToMany annotation, the back-reference could be useful in some use case, you have to see if you need it or not. Remember the back reference could cause problems with deserialization, creating a stack overflow by circular reference. You can avoid this, using transient keyword or various annotation (depending on the library you are using, Jackson, Gson, ecc..).
Be careful to don't use FetchType.EAGER randomly here's the why => Difference between FetchType LAZY and EAGER in Java Persistence API?
Related
using spring data and mysql as persistence layer getting some issues in Many to many mappings
#Getter
#Setter
public class BusinessUnitEntitiy extends AbstractTenantEntity implements Auditable{
private static final long serialVersionUID = -1123383144979037984L;
#Column(name = "NAME")
String name;
#Column(name = "DESCRIPTION")
String description;
#ManyToMany(fetch = FetchType.LAZY,mappedBy = "businessUnits" )
private Set<User> businessUsers;
public Set<User> fetchBusinessUsers() {
return businessUsers;
}
#Column(name = "DISPLAY_SEQUENCE_NUM")
protected Long displaySequenceNum;
#Column(name = "UNIQUE_SEQUENCE_ID",unique = true)
protected String uniqueSequenceId;
}
#Getter
#Setter
public class User extends AbstractTenantEntity {
private static final long serialVersionUID = 65981149772133526L;
#Column(name = "PROVIDER_USER_ID")
private String providerUserId;
private String email;
#Column(name = "enabled", columnDefinition = "BIT", length = 1)
private boolean enabled;
#Column(name = "DISPLAY_NAME")
private String displayName;
private String password;
private String provider;
#Column(name = "DISPLAY_SEQUENCE_NUM")
protected Long displaySequenceNum;
#Column(name = "UNIQUE_SEQUENCE_ID",unique = true)
protected String uniqueSequenceId;
#ManyToMany(fetch = FetchType.EAGER)
#JoinTable(
name = "business_unit_user",
joinColumns={#JoinColumn(name ="user_id")},
inverseJoinColumns = { #JoinColumn(name="business_unit_id") }
)
Set<BusinessUnitJpaEntitiy> businessUnits;
}
fetching the user from businessunit works perfectly
but fetching businessunits from users gives null set even updating the same user is persisiting only the newly linked businessunit older values vanishes
If you persisted the user within the transaction without initializing the businessUnits fields, that's what you get. Either you also initialize the set correctly before persisting, or you detach the user after persisting, so that the user is reloaded from the database and the set is properly initialized.
you can try this
#ManyToMany
#JoinTable(
name = "business_unit_user",
joinColumns={#JoinColumn(name ="user_id",referencedColumnName = "id")},
inverseJoinColumns = { #JoinColumn(name="business_unit_id",referencedColumnName = "id") }
)
Set<BusinessUnitJpaEntitiy> businessUnits;
and you must have setter and getter for each property
I am trying to add multiple entities in a single entity, I don't know this way possible or not please refer to my below code and help
the below code are the entity tables
#Entity
#Table(name = "agent_employee")
public class AgentEmployee extends Agent implements Serializable{
private static final long serialVersionUID = 1L;
#OneToMany // unidirectional
#JoinColumn(name = "employment_id", referencedColumnName = "id")
List<Employment> employmnet = new ArrayList<Employment>();
#OneToMany(
mappedBy = "agent",
cascade = CascadeType.ALL,
orphanRemoval = true
)
private Set<Officess> officess = new HashSet<>();
public List<Employment> getEmploymnet() {
return employmnet;
}
public void setEmploymnet(List<Employment> employmnet) {
this.employmnet = employmnet;
}
public Set<Officess> getOfficess() {
return officess;
}
public void setOfficess(Set<Officess> officess) {
this.officess = officess;
}
}
and Employment class is
#Data
#Entity
public class Employment {
#Id
#Column(nullable = false, unique = true)
private Long id;
private String empName;
private String location;
#Override
public String toString() {
return "Employment [id=" + id + ", empName=" + empName + ", location=" + location + "]";
}
}
and Offices class is
#Data
#Entity
#Table(name = "officess")
public class Officess implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String officeName;
#ManyToOne
#JoinColumn(name = "agent_emp")
private AgentEmployee agent;
}
And I have used spring boot repositories to all the respective entities
#GetMapping(path = "/add")
public #ResponseBody String addAgentEmployee() {
try {
AgentEmployee agemp = new AgentEmployee();
agemp.setFirstName("harish");
agemp.setLastName("kadsuru");
agemp.setEmail("hari**********is.net");
Employment emp1 = new Employment();
Employment emp2 = new Employment();
Employment emp3 = new Employment();
emp1.setId(501l);
emp2.setId(502l);
emp3.setId(503l);
emp1.setEmpName("junior engineer");
emp2.setEmpName("senior engineer");
emp3.setEmpName("team leader");
emp1.setLocation("bengaluru");
emp2.setLocation("mumbai");
emp3.setLocation("UAE");
List<Employment> emps = Arrays.asList(emp1, emp2, emp3);
employmentRepository.saveAll(emps);
agemp.setEmploymnet(emps);
agentEmployeeRepository.save(agemp);
return "saved";
} catch (Exception e) {
return "unable to save data due to exception";
}
}
#GetMapping("addOffice")
public #ResponseBody String addAgentEmployeeOffice() {
AgentEmployee emp;
Optional<AgentEmployee> agemp = agentEmployeeRepository.findById(27l);
if (agemp.isPresent()) {
emp = agemp.get();
}
else {
emp =new AgentEmployee();
emp.setFirstName("garish");
emp.setLastName("tumkur");
emp.setEmail("garish.kr#cyclotis.net");
}
log.info("###### {}",agemp);
Officess off1 = new Officess();
Officess off2 = new Officess();
Officess off3 = new Officess();
off1.setOfficeName("Google");
off2.setOfficeName("facebook");
off3.setOfficeName("Instagram");
Set<Officess> offices = emp.getOfficess();
offices.add(off1);
offices.add(off2);
offices.add(off3);
agentEmployeeRepository.save(emp);
log.info("######## {}", offices);
return "saved";
}
I don't think any problem with code, but I think I have a problem while saving the data. Kindly any body refer the correct way to analyse this problem.
Looks like your mapping is not correct. Also verify you have a EMPID column.
You don't need to use the #JoinTable annotation in your case.
As you are saving data you should use #PostMapping
StatusReport - removed private BigInteger EMPID; as it is used in joining
#Entity
#Table(name="statusreport")
public class StatusReport {
private BigInteger COMPLIANCEID;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private BigInteger STATUSRPTID;
private String COMMENTS;
private Date CREATEDDATE;
private BigInteger DEPARTMENT_ID;
#OneToOne
#JoinColumn(name = "EMPID")
private Employees employee;
//others methods
}
Employee - removed private BigInteger DEPARTMENT_ID; as it is used in joining
#Entity
public class Employees {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private BigInteger EMPID;
private String FIRSTNAME;
private String LASTNAME;
private Date DOB;
private String EMAIL;
#OneToOne
#JoinColumn(name = "DEPARTMENT_ID")
private Department department;
//others methods
}
Pardon me if this looks too basic, I am just a beginner in springboot. I am trying to create a simple project. I have entity class "company.java" and another "jobs.java"
I have already mapped them such that it will be saving both "companyID,jobID"
now my question is here :
1) how can I ensure that the record is captured into that new table when i feed data from thymeleaf fields. I have tried a dummy entry and its saving jobs into the jobs table but its not capturing anything to insert into the joined table
2) How do I query such that it saves and also when I search a job by its ID it shows me the company.
#Entity
#Table(name = "company_account")
#EntityListeners(AuditingEntityListener.class)
#SecondaryTable(name = "company_profile")
public class CompanyAccount {
private int id;
private String CompanyName;
private String PhoneNumber;
private String Number_of_employees;
private String CompanyURL;
private String OrganisationType;
private String PrimaryIndustry;
private byte[] Logo;
private String Location;
private String DateEstablished;
private String Headquarters;
private String SocialMedia;
public CompanyAccount() {
}
///////////////////////here i tried the mapping
#OneToMany(fetch = FetchType.LAZY, mappedBy = "company_account")
private List<NewJobs> jobs = new ArrayList<NewJobs>();
#Id
// #org.hibernate.annotations.ColumnDefault("001")
#GeneratedValue(strategy = GenerationType.AUTO)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
//////////////////////////////////
deleted the getters and setters
///////////////////////////////////////////////////////////////
#Entity
#Table(name = "newjobs")
#EntityListeners(AuditingEntityListener.class)
public class NewJobs {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#org.hibernate.annotations.ColumnDefault("001")
private int newjobid;
public NewJobs() {
}
tried my mapping here
#ManyToOne(fetch = FetchType.LAZY)
// #JoinColumn(name = "company_account")
#JoinTable(name = "company_jobs", joinColumns = { #JoinColumn(name = "id") }, inverseJoinColumns = {
#JoinColumn(name = "newjobid") })
private CompanyAccount CompanyAccount;
}
How can I query my insert and also my search by id ?
I have three classes - Document, Page, Sentence. A Document will have multiple Pages & each Page will have multiple Sentences. I'm trying to map One to Many relationship using Spring Data JPA annotation. But it only works when there are only one layer like - Document>Page. Doesn't work while it's Document>Page>Sentence.
Can anyone please give me a solution for how to do it for nested one to many relationship ?
My classes are given below.
#Entity
#Table(name = "DOCUMENT")
public class Document implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "FILEID")
#GeneratedValue(strategy = GenerationType.AUTO)
private long idFile;
#Lob
#Column(name = "CONTENT")
private byte[] content;
#Column(name = "NAME")
private String name;
#Column(name = "ID_MAIL_USER")
private String idMailUser;
#Column(name = "NUM_PAGES")
private int numPages;
#Column(name = "TO_ANALIZE")
private boolean toAnalize;
#Column(name = "HASH")
private String hash;
#Column(name = "EXTENSION")
private String extension;
#Column(name = "SIZE")
private double size;
#Column(name = "LINK_TO_DRIVE_FILE")
private String linkToDriveFile;
#Column(name="PATH")
private String path;
#OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
#Column(name = "PAGES")
private List<Page> pages = new ArrayList<>();
// Setter Getters
}
.
#Entity
#Table(name = "PAGE")
public class Page implements Serializable {
#Id
#Column(name = "PAGE_ID")
#GeneratedValue(strategy = GenerationType.AUTO)
private long idPage;
#Column(name = "PAGE_NUMBER")
private int pageNum;
#Lob
#Column(name = "CONTENT")
private String content;
#ManyToMany(cascade = CascadeType.ALL)
#Column(name = "SENTENCES")
private List<Sentence> sentences = new ArrayList<>();
// Setter Getters
}
.
#Entity
#Table(name = "SENTENCE")
public class Sentence implements Serializable {
//private long idFile;
//private long idPage;
#Id
#Column(name = "SENTENCE_ID")
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#Column(name = "PAGE_NUMBER")
private int pageNumber;
#Column(name = "ORDER")
private int ord;
#Column(name = "CONTENT")
private String content;
#Column(name = "HASH")
private String hash;
// Setter Getters
}
Your OneToMany mappings are incorrect. Correct it as follows
#Entity
#Table(name = "DOCUMENT")
public class Document implements Serializable {
......
#OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
#JoinColumn(name = "DOCUMENT_ID") //Name the foreign key column in PAGE table to DOCUMENT_ID
private List<Page> pages = new ArrayList<>();
}
#Entity
#Table(name = "PAGE")
public class Page implements Serializable {
....
#OneToMany(cascade = CascadeType.ALL)
#JoinColumn(name = "PAGE_ID") //Name the forein key column in PAGE table to PAGE_ID
private List<Sentence> sentences = new ArrayList<>();
}
Use #JoinColumn annotation instead of #Column to give the name of the foreign key that do the physical mapping between tables in your database.
#Entity
#Table(name = "DOCUMENT")
public class Document implements Serializable {
private static final long serialVersionUID = 1L;
#OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy="document")
#Column(name = "PAGES")
private List<Page> pages = new ArrayList<>();
}
#Entity
#Table(name = "PAGE")
public class Page implements Serializable {
#ManyToOne
#JoinColumn(name="DOCUMENT_ID")
private Document document;
#ManyToMany(cascade = CascadeType.ALL, mappedBy="pages")
#Column(name = "SENTENCES")
private List<Sentence> sentences = new ArrayList<>();
}
#Entity
#Table(name = "SENTENCE")
public class Sentence implements Serializable {
#ManyToMany(mappedBy="sentences")
private List<Page> pages;
}
Here a Document One to Many relationship with Pages.
So.. we need define mappedBy in the entity we want to map another entity.. so in this case
#OneToMany(mappedBy="document",cascade = CascadeType.ALL, orphanRemoval = true)
and in referenced entity i.e. Pages we want foreign key DOCUMENT_ID, so we have to define it using
#ManyToOne
#JoinColumn(name="DOCUMENT_ID")
Hello I'm trying to make an example of persistence of a OneToMany relationship in which I get the following error:
Exception Description: Invalid composite primary key specification. The names of the primary key fields or properties in the primary key class [entitys.OrderItemPK] and those of the entity bean class [class entitys.OrderItem] must correspond and their types must be the same. Also, ensure that you have specified ID elements for the corresponding attributes in XML and/or an #Id on the corresponding fields or properties of the entity class.
Note: I'm using EclipseLink and MySQL DB
The entities:
#Entity
public class CustomerOrder implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "idOrder")
private Integer idOrder;
#Basic(optional = false)
#Column(name = "orderText")
private String orderText;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "customerOrder")
private Collection<OrderItem> orderItemCollection;
public CustomerOrder() {
}
}
#Entity
#IdClass(OrderItemPK.class)
public class OrderItem implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
protected OrderItemPK orderItemPK;
#Basic(optional = false)
#Column(name = "itemDesc")
private String itemDesc;
#Id
#ManyToOne(optional = false)
#JoinColumns({
#JoinColumn(name="idOrder", referencedColumnName="idOrder"),
#JoinColumn(name="ItemNumber", referencedColumnName="ItemNumber")
})
//#JoinColumn(name = "idOrder", referencedColumnName = "idOrder", insertable = false, updatable = false)
private CustomerOrder customerOrder;
private CustomerOrder customerOrder;
public OrderItem() {
this.orderItemPK = new OrderItemPK();
}
}
#Embeddable
public class OrderItemPK implements Serializable {
#Basic(optional = false)
#Column(name = "idOrder")
private int idOrder;
#Basic(optional = false)
#Column(name = "itemNumber")
private int itemNumber;
public OrderItemPK() {
}
}
The test Source:
public static void main(String[] args) {
factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
EntityManager em = factory.createEntityManager();
em.getTransaction().begin();
// Fill the items fileds
OrderItem item = new OrderItem();
item.setItemDesc("Item Text");
// Fill the orders fields
CustomerOrder order = new CustomerOrder();
order.setOrderText("Order text");
// Fill the relationship fields
order.getOrderItemCollection().add(item);
item.setCustomerOrder(order);
em.persist(order);
em.getTransaction().commit();
}
I have no idea what I'm doing wrong, any suggestions are welcome.
Well i managed to solve the problem by removing idClass annotation and adding the #MapId
heres the final code:
#Entity
#Table(name = "Orders")
public class CustomerOrder implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "idOrder")
private Integer idOrder;
#Basic(optional = false)
#Column(name = "orderText")
private String orderText;
#OneToMany(mappedBy = "customerOrder", cascade = CascadeType.ALL)
private Collection<OrderItem> orderItemCollection;
public CustomerOrder() {
}
#Entity
#Table(name = "OrdersItems")
public class OrderItem implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
protected OrderItemPK orderItemPK;
#Basic(optional = false)
#Column(name = "itemDesc")
private String itemDesc;
#MapsId("idOrder")
#ManyToOne(optional = false)
#JoinColumn(name = "idOrder", referencedColumnName = "idOrder", nullable = false)
private CustomerOrder customerOrder;
public OrderItem() {
this.orderItemPK = new OrderItemPK();
}
#Embeddable
public class OrderItemPK implements Serializable {
#Basic(optional = false)
#Column(name = "idOrder")
private int idOrder;
#Basic(optional = false)
#Column(name = "itemNumber")
private int itemNumber;
public OrderItemPK() {
}
public static void main(String[] args) {
factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
EntityManager em = factory.createEntityManager();
em.getTransaction().begin();
// Fill the order item
OrderItem item = new OrderItem();
item.getOrderItemPK().setItemNumber(1);
item.setItemDesc("Product Name");
// Fill the order
CustomerOrder order = new CustomerOrder();
order.setOrderText("Testing");
// Create relationship
order.getOrderItemCollection().add(item);
item.setCustomerOrder(order);
// Persist
em.persist(order);
em.getTransaction().commit();
}
But i can't get it work with IdClass, here's the source
#Embeddable
public class OrderItemPK implements Serializable {
#Basic(optional = false)
#Column(name = "idOrder")
private Integer idOrder;
#Basic(optional = false)
#Column(name = "ItemNumber")
private Integer itemNumber;
public OrderItemPK() {
}
#Entity
#IdClass(OrderItemPK.class)
public class OrderItem implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "itemNumber")
private Integer itemNumber;
#Basic(optional = false)
#Column(name = "itemDesc")
private String itemDesc;
#MapsId("idOrder")
#ManyToOne(optional = false)
#JoinColumn(name = "idOrder", referencedColumnName = "idOrder", nullable = false)
private CustomerOrder customerOrder;
public OrderItem() {
}
#Entity
public class CustomerOrder implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "idOrder")
private Integer idOrder;
#Basic(optional = false)
#Column(name = "OrderText")
private String orderText;
#OneToMany(mappedBy = "customerOrder", cascade = CascadeType.ALL)
private Collection<OrderItem> orderItemCollection;
public CustomerOrder() {
this.orderItemCollection = new ArrayList();
}
Use MapsId in OrderItem:
#Entity
public class OrderItem implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
protected OrderItemPK orderItemPK;
#Basic(optional = false)
#Column(name = "itemDesc")
private String itemDesc;
#MapsId("idOrder")
#ManyToOne(optional = false)
#JoinColumn(name = "idOrder", referencedColumnName = "idOrder")
private CustomerOrder customerOrder;
}
An alternative is to remove the embedded id and use an ID class:
#Entity
#IdClass(OrderItemPK.class)
public class OrderItem implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "itemNumber")
private int itemNumber;
#Basic(optional = false)
#Column(name = "itemDesc")
private String itemDesc;
#Id
#ManyToOne(optional = false)
#JoinColumn(name = "idOrder", referencedColumnName = "idOrder")
private CustomerOrder customerOrder;
}
public class OrderItemPK implements Serializable {
//name of the relation in the entity, but same type as the CustomerOrder PK.
int customerOrder;
int itemNumber;
public OrderItemPK() {
}
}