Can someone help me with a simple explanation of how to use #Embeddable ?
I have this situation below!
One company, has several employees, and my employee table has 2 ID fields (register_number and name)
Is this the right approach?
#Entity
#Table(name = "COMPANY")
public class Company implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
private Employee employeeId;
#Id
#GeneratedValue(strategy = GenerationType.AUTO, generator = "native")
#GenericGenerator(name = "native", strategy = "native")
#Column(name = "ID", unique = true, nullable = false, precision = 38)
private Long id;
#Column(name = "NAME", nullable = false, length = 50)
private String name;
#ToString.Exclude
#EqualsAndHashCode.Exclude
#OneToMany(fetch = FetchType.LAZY, mappedBy = "registerNumber")
private Set<Employee> employees;
}
//
#Embeddable
#Entity
#Table(name = "EMPLOYEE")
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
#Column(name = "REGISTER_NUMBER", nullable = false, length = 100)
private String registerNumber;
#Column(name = "NAME", nullable = false, length = 50)
private String name;
#Column(name = "EMAIL", nullable = false, length = 50)
private String email;
}
I think you are looking a way to support composite key using hibernate. You should move those fields to a new class and annotate that class with #Embeddable.
For classes mentioned in the question, create a new Embeddable class EmployeeIdClass with the fields (registerNumber and name), and have a variable for this class's object in Employee, annotate it with #EmbeddedId.
EmployeeIdClass
#Embeddable
public class EmployeeIdClass implements Serializable{
#Column(name = "REGISTER_NUMBER", nullable = false, length = 100)
private String registerNumber;
#Column(name = "NAME", nullable = false, length = 50)
private String name;
public String getRegisterNumber() {
return registerNumber;
}
public void setRegisterNumber(String registerNumber) {
this.registerNumber = registerNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
EmployeeIdClass that = (EmployeeIdClass) o;
return Objects.equals(registerNumber, that.registerNumber) &&
Objects.equals(name, that.name);
}
#Override
public int hashCode() {
return Objects.hash(registerNumber, name);
}
}
Employee
#Entity
#Table(name = "EMPLOYEE")
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
#Column(name = "employeeId", nullable = false, length = 50)
private EmployeeIdClass employeeId;
#Column(name = "EMAIL", nullable = false, length = 50)
private String email;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public EmployeeIdClass getEmployeeId() {
return employeeId;
}
public void setEmployeeId(EmployeeIdClass employeeId) {
this.employeeId = employeeId;
}
}
Company
#Entity
#Table(name = "COMPANY")
public class Company implements Serializable {
private static final long serialVersionUID = 1L;
// #EmbeddedId
// private Employee employeeId;
#Id
#GeneratedValue(strategy = GenerationType.AUTO, generator = "native")
#GenericGenerator(name = "native", strategy = "native")
#Column(name = "ID", unique = true, nullable = false, precision = 38)
private Long id;
#Column(name = "NAME", nullable = false, length = 50)
private String name;
// #ToString.Exclude
// #EqualsAndHashCode.Exclude
#OneToMany(fetch = FetchType.LAZY)
private Set<Employee> employees;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Employee> getEmployees() {
return employees;
}
public void setEmployees(Set<Employee> employees) {
this.employees = employees;
}
}
CompanyEmployeeTest
public class CompanyEmployeeTest {
public static void main(String[] args) {
EmployeeIdClass employeeIdClass2 = new EmployeeIdClass();
employeeIdClass2.setName("b");
employeeIdClass2.setRegisterNumber("2");
EmployeeIdClass employeeIdClass3 = new EmployeeIdClass();
employeeIdClass3.setName("c");
employeeIdClass3.setRegisterNumber("3");
Employee emp2 = new Employee();
emp2.setEmail("b#");
Employee emp3 = new Employee();
emp3.setEmail("c#");
emp2.setEmployeeId(employeeIdClass2);
emp3.setEmployeeId(employeeIdClass3);
Company company = new Company();
Set<Employee> set = new HashSet<>();
set.add(emp2);
set.add(emp3);
company.setEmployees(set);
company.setName("first-company");
company.setId(1234l);
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
session.save(company);
session.save(emp3);
session.save(emp2);
transaction.commit();
session.close();
}
}
Queries ran by Hibernate
Hibernate: create table COMPANY (ID bigint not null auto_increment, NAME varchar(50) not null, primary key (ID)) engine=MyISAM
Hibernate: create table COMPANY_EMPLOYEE (Company_ID bigint not null, employees_NAME varchar(50) not null, employees_REGISTER_NUMBER varchar(100) not null, primary key (Company_ID, employees_NAME, employees_REGISTER_NUMBER)) engine=MyISAM
Hibernate: create table EMPLOYEE (NAME varchar(50) not null, REGISTER_NUMBER varchar(100) not null, EMAIL varchar(50) not null, primary key (NAME, REGISTER_NUMBER)) engine=MyISAM
Hibernate: alter table COMPANY_EMPLOYEE add constraint UK_lnmh1scqoa65gxcryjyeroyj unique (employees_NAME, employees_REGISTER_NUMBER)
Hibernate: alter table COMPANY_EMPLOYEE add constraint FKkkjhj0prbvia5yiqebnefkkb5 foreign key (employees_NAME, employees_REGISTER_NUMBER) references EMPLOYEE (NAME, REGISTER_NUMBER)
Hibernate: alter table COMPANY_EMPLOYEE add constraint FKivik2ern4s4074u9eb3c6u7jw foreign key (Company_ID) references COMPANY (ID)
Hibernate: insert into COMPANY (NAME) values (?)
Hibernate: insert into EMPLOYEE (EMAIL, NAME, REGISTER_NUMBER) values (?, ?, ?)
Hibernate: insert into EMPLOYEE (EMAIL, NAME, REGISTER_NUMBER) values (?, ?, ?)
Hibernate: insert into COMPANY_EMPLOYEE (Company_ID, employees_NAME, employees_REGISTER_NUMBER) values (?, ?, ?)
Hibernate: insert into COMPANY_EMPLOYEE (Company_ID, employees_NAME, employees_REGISTER_NUMBER) values (?, ?, ?)
Related
I have Employee
#Entity
public class Employee {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE)
private Integer employeeId;
#Basic(optional=false)
private String employeeName;
#OneToMany(cascade=CascadeType.ALL)
#JoinColumns({
#JoinColumn(name="employeeId",referencedColumnName="employeeId",
updatable = false, insertable = true)
})
private List<Address> address;
//getters and setters
}
Address
#Entity(name="address")
#Table(uniqueConstraints = { #UniqueConstraint(columnNames = {"employeeId", "AddressId"})})
public class Address {
private String addressCountry;
private String addressCity;
#AttributeOverrides({
#AttributeOverride(name = "employeeId", column = #Column(name = "employeeId", nullable = false))//,
//#AttributeOverride(name = "idCorporativeEvent", column = #Column(name = "id_corporative_event", nullable = false))
})
#EmbeddedId
private AddressPK addressId;
//getters and setters
}
AddressPK
#Embeddable
public class AddressPK implements Serializable{
#Column(name="employeeId", insertable = true, updatable = true)
private Integer employeeId;
#Column(name="AddressId")
private Integer addressId;
public Integer getEmployeeId() {
return employeeId;
}
public void setEmployeeId(Integer employeeId) {
this.employeeId = employeeId;
}
public Integer getAddressId() {
return addressId;
}
public void setAddressId(Integer addressId) {
this.addressId = addressId;
}
public boolean equals(Object obj){
if(obj instanceof AddressPK){
AddressPK addPK = (AddressPK) obj;
if(this.addressId == addPK.getAddressId() &&
this.employeeId == addPK.getEmployeeId()
){
return true;
}
}
else {
return false;
}
return false;
}
public int hashCode(){
return super.hashCode();
}
}
I'm create object Employee and try save it:
Employee employee = new Employee();
//employee.setEmployeeId(1);
employee.setEmployeeName("John Smith");
Address address = new Address();
AddressPK addressPK = new AddressPK();
addressPK.setAddressId(1);
//addressPK.setEmployeeId(1);
address.setAddressId(addressPK);
address.setAddressCountry("United Kingdom");
address.setAddressCity("London");
List<Address> listAddr = new ArrayList<Address>();
listAddr.add(address);
employee.setAddress(listAddr);
serviceUser.save(empl);
I get error:
ERROR: null value in column "employeeid" violates not-null constraint: Failing row contains (1, null, London, United Kingdom).
When I remove
#GeneratedValue(strategy = GenerationType.SEQUENCE)
And add
employee.setEmployeeId(1);
addressPK.setEmployeeId(1);
I'm success. Why I get error null value?
Thank's
I have two tables in db employee and department as:
CREATE TABLE test.employee (
EMPID int(10) unsigned NOT NULL DEFAULT '1',
Name varchar(45) NOT NULL DEFAULT '1',
DEPTID int(10) unsigned NOT NULL DEFAULT '1',
PRIMARY KEY (EMPID),
KEY FK_employee_1 (DEPTID),
CONSTRAINT FK_employee_1 FOREIGN KEY (DEPTID) REFERENCES department (DEPTID)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE test.department (
DEPTID int(10) unsigned NOT NULL AUTO_INCREMENT,
Name varchar(45) NOT NULL,
PRIMARY KEY (DEPTID)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
And my mapping classes are as below:
Employee2.java
#Entity
#Table(name="EMPLOYEE")
public class Employee2 {
#Id #GeneratedValue
#Column(name="EMPID")
private String ID;
#Column(name="Name")
private String Name;
#Column(name="DEPTID")
private String DepartmentID;
public Employee2(String iD, String name, String departmentID){
ID = iD;
Name = name;
DepartmentID = departmentID;
}
public Employee2(){
}
public String getID() {
return ID;
}
public void setID(String iD) {
ID = iD;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getDepartmentID() {
return DepartmentID;
}
public void setDepartmentID(String departmentID) {
DepartmentID = departmentID;
}
#OneToOne
#JoinColumn(table = "DEPARTMENT", name = "DEPTID", referencedColumnName="DEPTID")
private Department2 ec;
public Department2 getEc() {
return ec;
}
public void setEc(Department2 ec) {
this.ec = ec;
}
}
Department2.java
#Entity
#Table(name="DEPARTMENT")
public class Department2 {
#Id #GeneratedValue
#Column(name="DEPTID")
private String ID;
#Column(name="Name")
private String Name;
public Department2(String iD, String name) {
ID = iD;
Name = name;
}
public Department2(){
}
public String getID() {
return ID;
}
public void setID(String iD) {
ID = iD;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
}
I want to select from two tables with join as EMPLOYEE.DEPTID = DEPARTMENT.DEPTID
I dont want to write query.
Here is how I m doing it in test class
tx = session.beginTransaction();
Criteria criteria = session.createCriteria(Employee2.class, "employee").
createCriteria("employee.ec", JoinType.INNER_JOIN);
List<Equipment2> rows = criteria.list();
System.out.println(rows.size());
tx.commit();
But I m getting following exception
Failed to create sessionFactory object.org.hibernate.AnnotationException: Cannot find the expected secondary table: no DEPARTMENT available for com.cts.sm.Employee2
Exception in thread "main" java.lang.ExceptionInInitializerError
I m using Hibernate 4.2
Can you please help me as what I m missing in this.
As suggested by #jpprade
Make the following change
#ManyToOne
#JoinColumn(name ="DEPTID", updatable = false, insertable = false)
private Department2 ec;
//getter setter
Thanks
N G
I am really stuck in solving the below error. Please help me to make it solve ?
I'm developing ManyToMany relationship example.
Initial SessionFactory creation failed.org.hibernate.MappingException: Foreign key (FK302BCFEEB260666:category [CATEGORY_ID])) must have same number of columns as the referenced primary key (category [STOCK_ID,CATEGORY_ID])
Exception in thread "main" java.lang.ExceptionInInitializerError
at com.mkyong.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:17)
at com.mkyong.util.HibernateUtil.<clinit>(HibernateUtil.java:8)
at com.mkyong.App.main(App.java:13)
Caused by: org.hibernate.MappingException: Foreign key (FK302BCFEEB260666:category [CATEGORY_ID])) must have same number of columns as the referenced primary key (category [STOCK_ID,CATEGORY_ID])
at org.hibernate.mapping.ForeignKey.alignColumns(ForeignKey.java:112)
at org.hibernate.mapping.ForeignKey.alignColumns(ForeignKey.java:95)
at org.hibernate.cfg.Configuration.secondPassCompileForeignKeys(Configuration.java:1808)
at org.hibernate.cfg.Configuration.originalSecondPassCompile(Configuration.java:1729)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1396)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1829)
at com.mkyong.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:13)
... 2 more
The code I developed,
Category.java
#Entity
#Table(name = "category")
public class Category implements java.io.Serializable {
private static final long serialVersionUID = 8833944947723156024L;
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "CATEGORY_ID", unique = true, nullable = false)
private Integer categoryId;
#Column(name = "NAME", nullable = false, length = 10)
private String name;
#Column(name = "DESCRIPTION", nullable = false)
private String desc;
#ManyToMany(fetch = FetchType.LAZY, mappedBy = "categories")
private Set<Stock> stocks = new HashSet<Stock>(0);
public Category() { }
public Category(String name, String desc) {
this.name = name;
this.desc = desc;
}
public Category(String name, String desc, Set<Stock> stocks) {
this.name = name;
this.desc = desc;
this.stocks = stocks;
}
// setters and getters
}
Stock.java
#Entity
#Table(name = "stock",uniqueConstraints = {
#UniqueConstraint(columnNames = "STOCK_NAME"),
#UniqueConstraint(columnNames = "STOCK_CODE") })
public class Stock implements java.io.Serializable {
private static final long serialVersionUID = 7788035862084120942L;
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "STOCK_ID", unique = true, nullable = false)
private Integer stockId;
#Column(name = "STOCK_CODE", unique = true, nullable = false, length = 10)
private String stockCode;
#Column(name = "STOCK_NAME", unique = true, nullable = false, length = 20)
private String stockName;
#ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinTable(name = "category",
joinColumns = { #JoinColumn(name = "STOCK_ID", nullable = false, updatable = false) },
inverseJoinColumns = { #JoinColumn(name = "CATEGORY_ID")})
private Set<Category> categories = new HashSet<Category>(0);
public Stock() { }
public Stock(String stockCode, String stockName) {
this.stockCode = stockCode;
this.stockName = stockName;
}
public Stock(String stockCode, String stockName, Set<Category> categories) {
this.stockCode = stockCode;
this.stockName = stockName;
this.categories = categories;
}
// setters and getters
}
HibernateUtil.java
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdown() {
// Close caches and connection pools
getSessionFactory().close();
}
}
App.java
public class App {
public static void main(String[] args) {
System.out.println("Hibernate many to many (Annotation)");
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Stock stock = new Stock();
stock.setStockCode("7052");
stock.setStockName("PADINI");
Category category1 = new Category("CONSUMER", "CONSUMER COMPANY");
Category category2 = new Category("INVESTMENT", "INVESTMENT COMPANY");
Set<Category> categories = new HashSet<Category>();
categories.add(category1);
categories.add(category2);
stock.setCategories(categories);
session.save(stock);
session.getTransaction().commit();
System.out.println("Done");
}
}
Please help me what is wrong here?
create table stock(
stock_id BIGINT(10) NOT NULL AUTO_INCREMENT,
stock_code VARCHAR(50),
stock_name VARCHAR(50),
PRIMARY KEY (`stock_id`)
);
create table Category(
stock_id BIGINT(10) NOT NULL AUTO_INCREMENT,
category_id VARCHAR(50),
name VARCHAR(50),
description VARCHAR(50),
PRIMARY KEY (`stock_id`)
)
Edit-1:
Now I am getting below error?
Exception in thread "main" org.hibernate.exception.SQLGrammarException: Could not execute JDBC batch update
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:92)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:275)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:268)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:188)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1216)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:383)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:133)
at com.mkyong.App.main(App.java:31)
Caused by: java.sql.BatchUpdateException: Table 'test.stock_category' doesn't exist
at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:2024)
at com.mysql.jdbc.PreparedStatement.executeBatch(PreparedStatement.java:1449)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268)
... 8 more
The name of the join table is assumed to be the table names of the
associated primary tables concatenated together (owning side first)
using an underscore.
In this case Join Table is stock_category
#JoinTable(name = "stock_category",
joinColumns = { #JoinColumn(name = "STOCK_ID", nullable = false, updatable = false) },
inverseJoinColumns = { #JoinColumn(name = "CATEGORY_ID")})
I have a Entity class named as Employee
#Entity
#Table(name = "employee")
#DynamicUpdate
public class Employee {
private String empId;
private String name;
private String employeeDefaultCountry;
#Id
#Column(name="emp_id", nullable=false, insertable=true, updatable=true, length=8)
public String getEmpId() {
return empId;
}
public void setEmpId(String empId) {
this.empId= empId;
}
...
}
employeeDefaultCountry is defined in other table "system_defaults" and there is no primary and foreign key relation between these two tables(employee and system_defaults).
However a constant value will be provided for system_defaults id(PK) that is constant 1. How can i achieve it?
Achieving via Native SQL:
select empId,name,(select employee_default_country from system_defaults where id=1) as DefaultCountry from employee.
Output:
empId,Name,DefaultCountry
101,Ahmed,India
103,Parkash,India
...
I want to achieve this in JPA.
Note: This DefaultCountry field should be readable, when saving to DB it should not write.
employee Table fields(emp_id(VARCHAR2),name(VARCHAR2)) only two fields
system_parameters Table fields(id(INT),default_country(VARCHAR2),default_designation(VARCHAR2)) only three fields.
Entity of System_defaults:
#Entity
#Table(name = "system_defaults")
#DynamicUpdate
public class SystemDefaults {
Integer id;
String defaultCountry;
#Id
#Column(name = "id", nullable = false, insertable = false, updatable = false)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#Basic
#Column(name = "default_country", nullable = false, insertable = false, updatable = false, length = 40)
public String getDefaultCountry() {
return defaultCountry;
}
public void setDefaultCountry(String defaultCountry) {
this.defaultCountry = defaultCountry;
}
}
I have two class:
Order.java:
#Entity
#Table(name = "orders", catalog = "ownDB")
public class Order {
private int orderNO;
private String oderName;
private Set<Room> rooms = new HashSet<Room>(0);
public Order(int orderNo, String orderName, Set<Room> rooms) {
this.oderNo = orderNo;
this.orderName = orderName;
this.rooms = rooms;
}
#Id
#Column(name = "orderNO", unique = true, nullable = false, length = 6)
public int getOrderNO() {
return this.orderNO;
}
public void setOrderNo(int OrderNO) {
this.orderNO = orderNO;
}
#Column(name = "orderName", nullable = false, length = 100)
public String getOrderName() {
return this.orderName;
}
public void setOrderName(String orderName) {
this.orderName = orderName;
}
#ManyToMany(fetch = FetchType.EAGER)
#JoinTable(name = "rooms_orders", joinColumns = { #JoinColumn(name = "orderNO") }, inverseJoinColumns = { #JoinColumn(name = "roomNO") })
public Set<Room> getRoom() {
return this.rooms;
}
public void setRoom(Set<Room> rooms) {
this.rooms = rooms;
}
}
And this is the room.java:
#Entity
#Table(name = "rooms", catalog = "ownDB")
public class {
private int roomNO;
private String name;
private Set<Order> orders = new HashSet<Order>(0);
public Room(int roomNO, String name, Set<Order> orders) {
this.roomNO = roomNO;
this.name = name;
this.orders = orders;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "roomNO", unique = true, nullable = false, length = 6)
public int getRoomNO() {
return this.roomNO;
}
public void setRoomNO(int roomNO) {
this.roomNO = roomNO;
}
#Column(name = "name", nullable = false, length = 100)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
#ManyToMany(fetch = FetchType.EAGER)
#JoinTable(name = "rooms_orders", joinColumns = { #JoinColumn(name = "roomNO") }, inverseJoinColumns = { #JoinColumn(name = "orderNO") })
public Set<Order> getOrders() {
return this.orders;
}
public void setOrders(Set<Order> orders) {
this.orders = orders;
}
}
SQL:
CREATE TABLE rooms (
roomNO int(6) NOT NULL ,
name VARCHAR(100) NOT NULL ,
PRIMARY KEY (roomNO));
CREATE TABLE orders (
orderNO int(6) NOT NULL AUTO_INCREMENT,
orderName VARCHAR(100) NOT NULL,
PRIMARY KEY (orderNO));
CREATE TABLE rooms_orders (
roomNO int(6) NOT NULL,
orderNO int (6) NOT NULL,
PRIMARY KEY (roomNO, orderNO));
What is the problem with the two mapping? It is works for me. But I don't want to use, if it isn't the right way. If I am change the second mapping to "#ManyToMany(mappedBy="room")" (without the joinTable annotation) in the Order class. I can't list all rooms (with their orders), because I got this error message:
"Failed to lazily initialize a collection of role: com.room.model.Room.orders, could not initialize proxy - no Session"
What is the right way to can list all orders with their rooms and all rooms with their orders. So I need "two-way" join.
There are many errors in the code you posted.
First of all, your join table is not correctly defined. It shouldn't have a seperate column for the ID: noone will ever populate this column. It should be defined as
CREATE TABLE rooms_orders (
roomNO int(6) NOT NULL,
orderNO int (6) NOT NULL,
PRIMARY KEY (rommNO, orderNO));
Second, your mapping is wrong. A bidirectional association always has an owner side, which defines how the association is mapped, and an inverse side, which uses the mappedBy attribute to tell JPA that this is the inverse side, and where to find the owner side. So, in Room, the association should be mapped with
#ManyToMany(mappedBy = "rooms")
public Set<Order> getOrders() {
return this.orders;
}
And finally, your mapping for the association doesn't match with the column names in your table:
#JoinTable(name = "rooms_orders",
joinColumns = { #JoinColumn(name = "orderNO") },
inverseJoinColumns = { #JoinColumn(name = "roomNumber") })
There is no column "roomNumber" in the table. The column is named "roomNO".