I'm working on website where user can subscribe to Organisation.
when I'm going to implement Subscribe function and I face the following problem.
In sort I want to create model class of ManyToMany join table for retrieve rows from table to check which Organisations are subscribe by user.
And In Hibernate I can't create Table without primary key.but in join table one user can subscribe to many organisation and one organisation has many subscriber so primary key are repeat and I got exception ERROR: Duplicate entry '1' for key 'PRIMARY'.
hibernate.cfg.xml contain
<mapping class="model.User"/>
<mapping class="model.Post"/>
<mapping class="model.UserSubscribes"/>
User.java
package model;
#Entity
#Table(name="user",
uniqueConstraints = {#UniqueConstraint(columnNames={"email"})}
)
#org.hibernate.annotations.Entity(dynamicUpdate=true,selectBeforeUpdate=true)
public class User implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private long userId;//1
private String email;//1
private String password;//
public User(long userId, String email, String password){
this.userId = userId;
this.email = email;
this.password = password;
}
#ManyToMany(fetch = FetchType.LAZY)
#JoinTable(
name="UserSubscribes",
joinColumns={ #JoinColumn(name="userId",referencedColumnName="userId") },
inverseJoinColumns={ #JoinColumn(name="orgId", referencedColumnName="orgId") }
)
private Collection<Organisation> orgSubscribes = new ArrayList<Organisation>();
//Getter & Setter
}
Organisation.java
package model;
#Entity
#Table(name="org",
uniqueConstraints = {#UniqueConstraint(columnNames={"email"})}
)
#org.hibernate.annotations.Entity(dynamicUpdate=true,selectBeforeUpdate=true)
public class Organisation implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private long orgId;
private String email;
private String password;
public Organisation(long orgId, String email, String password){
this.orgId = orgId;
this.email = email;
this.password = password;
}
//Getter & Setter
}
UserSubscribes.java
package model;
#Entity
#Table(name="UserSubscribes")
public class UserSubscribes implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private long userId;
private long orgId;
//Getter & Setter
}
Subscribe.java
package view.action;
public class Subscribe extends ActionSupport {
public String execute(){
Session session = HibernateUtill.getSessionFactory().getCurrentSession();
session.beginTransaction();
System.out.println("Subscribbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
User u1 = new User(1, "ppp", "ppp");
User u2 = new User(2, "qqq", "qqq");
Organisation o1 = new Organisation(1, "ppp", "ppp");
Organisation o2 = new Organisation(2, "qqq", "qqq");
Organisation o3 = new Organisation(3, "www", "www");
Organisation o4 = new Organisation(4, "eee", "eee");
session.save(o1);
session.save(o2);
session.save(o3);
session.save(o4);
session.save(u1);
session.save(u2);
u1.getOrgSubscribes().add(o1);
u1.getOrgSubscribes().add(o2);
u1.getOrgSubscribes().add(o3);
session.saveOrUpdate(u1);
session.getTransaction().commit();
return SUCCESS;
}
}
and I got this output and error
Subscribbbbbbbbbbbbbbbbbbbbbbbbbbbbb
Hibernate: insert into org (email, password) values (?, ?)
Hibernate: insert into org (email, password) values (?, ?)
Hibernate: insert into org (email, password) values (?, ?)
Hibernate: insert into org (email, password) values (?, ?)
Hibernate: insert into user (email, password) values (?, ?)
Hibernate: insert into user (email, password) values (?, ?)
Hibernate: insert into UserSubscribes (userId, orgId) values (?, ?)
Hibernate: insert into UserSubscribes (userId, orgId) values (?, ?)
Apr 27, 2014 4:43:52 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 1062, SQLState: 23000
Apr 27, 2014 4:43:52 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Duplicate entry '1' for key 'PRIMARY'
If I remove <mapping class="model.UserSubscribes"/> from hibernate.cfg.xml mapping then it works perfect as following output.
Subscribbbbbbbbbbbbbbbbbbbbbbbbbbbbb
Hibernate: insert into org (email, password) values (?, ?)
Hibernate: insert into org (email, password) values (?, ?)
Hibernate: insert into org (email, password) values (?, ?)
Hibernate: insert into org (email, password) values (?, ?)
Hibernate: insert into user (email, password) values (?, ?)
Hibernate: insert into user (email, password) values (?, ?)
Hibernate: insert into UserSubscribes (userId, orgId) values (?, ?)
Hibernate: insert into UserSubscribes (userId, orgId) values (?, ?)
Hibernate: insert into UserSubscribes (userId, orgId) values (?, ?)
and output is
but I can't retrieve rows(using HQL) from it without map this table in hibernate.cfg.xml file.
If any possible solution for this problem I'm really thankful to you.
Thank you in advance.
The join table should not be mapped as an entity. You simply need User, Organization, and a ManyToMany association between those 2 entities.
In sort I want to create model class of ManyToMany join table for retrieve rows from table to check which Organisations are subscribe by user
That can be done with the association:
User user = em.find(User.class, userId);
Set<Organization> organizations = user.getOrganizations();
or with a simple JPQL query:
select o from User u inner join u.organizations o where u.id = :userId
Thanks JB Nizet
I implement code as you suggest and it works perfect.
Here is Solved Code.
GetSubscriber.java
package view.action;
public class GetSubscriber extends ActionSupport {
public String execute(){
Session session = HibernateUtill.getSessionFactory().getCurrentSession();
session.beginTransaction();
User u = (User) session.get(User.class, (long)1);
List<Organisation> s = (List<Organisation>) u.getOrgSubscribes();
for(int i=0;i<s.size();i++){
System.out.println(s.get(i).getOrgId() + " " + s.get(i).getEmail());
}
return SUCCESS;
}
}
Output:
1 ppp
2 qqq
3 www
Related
I have two tables with a one-to-many relationship. I want to fetch those records and insert into another database which having same table by changing the primary key.
My application entity class
#Entity
#Table(name = "EM_APPLICATION")
public class ApplicationTable {
#Id
private int APPLICATION_ID;
#Id
private String CUSTOMER_ID;
private String LAST_NAME;
private String FIRST_NAME;
#OneToMany( fetch = FetchType.EAGER,cascade = CascadeType.ALL)
#JoinColumns({ #JoinColumn(name = "CUSTOMER_ID", referencedColumnName = "CUSTOMER_ID"),
#JoinColumn(name = "APPLICATION_ID", referencedColumnName = "APPLICATION_ID") })
private Set<AddressTable> address;
//Getters and setters
}
Address entity class..
#Entity
#Table(name="EM_APPL_ADDRESS")
public class AddressTable{
#Id
private int APPLICATION_ID;
#Id
private String CUSTOMER_ID;
#Id
private String ADDRESS_TYPE;
//Getters and setters
}
I have to execute a method for fetching records from DB using hibernate:
public void execute(String applId, String customerId) {
Session session = HibernateQAUtil.openSession();
Transaction tx = session.beginTransaction();
String hql = "FROM ApplicationTable WHERE CUSTOMER_ID =:CUSTOMER_ID AND APPLICATION_ID =:APPLICATION_ID";
Query query = session.createQuery(hql);
query.setParameter("CUSTOMER_ID", customerId);
query.setParameter("APPLICATION_ID", Integer.parseInt(applId));
List<ApplicationTable> list = query.list();
tx.commit();
session.close();
ApplicationTable applVO = list.get(0);
insertApplication(applVO );
}
After fetching the records, I am changing APPLICATION_ID, CUSTOMER_ID and some other columns in address table and after inserting in another database.
private void insertApplication(ApplicationTable emApplVO) {
applVO.setAPPLICATION_ID(123456);
applVO.setCUSTOMER_ID("88888888");
Set<AddressTable> addressSet = emApplVO.getAddress();
for (AddressTable address : addressSet) {
address.setAPPLICATION_ID(123456);
address.setCUSTOMER_ID("88888888");
address.setZIP(500032);
}
Session session1 = HibernateUtil.openSession();
Transaction beginTransaction = session1.beginTransaction();
session1.save(emApplVO);
beginTransaction.commit();
session1.close();
}
Hibernate queries in console log are... (below mentioned queries are too large so copied to some extent only..)
Hibernate: select em_applica0_.CUSTOMER_ID as CUSTOMER1_0_,em_applica0_.APPLICATION_ID as APPLICAT2_0_,em_applica0_.ARCHIVE_IND as ARCHIVE8_0_ where em_applica0_.CUSTOMER_ID=? and em_applica0_.APPLICATION_ID=?
Hibernate: select address0_.CUSTOMER_ID as CUSTOMER1_0_1_, address0_.APPLICATION_ID as APPLICAT2_0_1_, address0_.ADDRESS_TYPE as ADDRESS3_1_0_ where em_applica0_.CUSTOMER_ID=? and em_applica0_.APPLICATION_ID=?
Hibernate: insert into EM_APPLICATION (CUSTOMER_ID, APPLICATION_ID, APPLICATION_NBR, APPLICATION_STATUS, APPLICATION_TYPE) values (?, ?, ?, ?)
Hibernate: insert into EM_APPL_ADDRESS (CUSTOMER_ID, APPLICATION_ID, ADDRESS_TYPE) values (?, ?, ?)
Question 1: in the insert method, I have assigned address to addresSet and made some changes in addresSet, after making those changes, I am not assigned the addressSet to applVO (i.e. not written applVO.setAddress(addresSet )) but it inserted a record with updated values into the Address table. What is happening here?
When I am changing code inside insertApplication(ApplicationTable emApplVO) method to
private void insertApplication(ApplicationTable emApplVO) {
applVO.setAPPLICATION_ID(123456);
applVO.setCUSTOMER_ID("88888888");
Set<AddressTable> addressSet = emApplVO.getAddress();
Set<AddressTable> newAddressSet = new HashSet<AddressTable>();
for (AddressTable address : newAddressSet) {
address.setAPPLICATION_ID(emApplVO.getAPPLICATION_ID());
address.setCUSTOMER_ID(emApplVO.getCUSTOMER_ID());
address.setZIP(500032);
newAddressSet.add(address);
}
emApplVO.setAddress(null);
emApplVO.setAddress(newAddressSet);
Session session1 = HibernateUtil.openSession();
Transaction beginTransaction = session1.beginTransaction();
session1.save(emApplVO);
beginTransaction.commit();
session1.close();
}
Hibernate queries in console log are... It also executing update ...
Hibernate: select em_applica0_.CUSTOMER_ID as CUSTOMER1_0_,em_applica0_.APPLICATION_ID as APPLICAT2_0_,em_applica0_.ARCHIVE_IND as ARCHIVE8_0_ where em_applica0_.CUSTOMER_ID=? and em_applica0_.APPLICATION_ID=?
Hibernate: select address0_.CUSTOMER_ID as CUSTOMER1_0_1_, address0_.APPLICATION_ID as APPLICAT2_0_1_, address0_.ADDRESS_TYPE as ADDRESS3_1_0_ where em_applica0_.CUSTOMER_ID=? and em_applica0_.APPLICATION_ID=?
Hibernate: insert into EM_APPLICATION (CUSTOMER_ID, APPLICATION_ID, APPLICATION_NBR, APPLICATION_STATUS, APPLICATION_TYPE) values (?, ?, ?, ?)
Hibernate: insert into EM_APPL_ADDRESS (CUSTOMER_ID, APPLICATION_ID, ADDRESS_TYPE) values (?, ?, ?)
update EM_APPL_ADDRESS set CUSTOMER_ID=?, APPLICATION_ID=? where CUSTOMER_ID=? and APPLICATION_ID=? and ADDRESS_TYPE=?
Question 2: why is the update query executed?
Question 3: while using List<AddressTable> instead of Set<AddressTable>, I got some errors. What is the difference?
I have model object as follows
Employee.java
#Entity
#Table(name = "EMPLOYEE")
public class Employee {
#Id
#SequenceGenerator(name = "emp_seq", sequenceName = "seq_employee")
#GeneratedValue(generator = "emp_seq")
#Column(name = "EMPLOYEE_ID")
private Integer employeeId;
#Column(name = "EMPLOYEE_NAME")
private String employeeName;
}
Department.java
#Entity
#Table(name = "DEPARTMENT")
public class Department {
#Id
#Column(name = "DEPARTMENT_ID")
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer departmentId;
#Column(name = "DEPARTMENT_NAME")
private String departmentName;
#Column(name = "LOCATION")
private String location;
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JoinColumn(name = "DEPARTMENT_ID")
private List<Employee> employees = new ArrayList<>();
}
while saving this it is generating two extra update statements.
Test class
Employee e1 = new Employee();
e1.setEmployeeName("Employee-1");
Employee e2 = new Employee();
e2.setEmployeeName("Employee-2");
Department d = new Department();
d.setDepartmentName("Test");
d.setLocation("Test");
d.getEmployees().add(e1);
d.getEmployees().add(e2);
em.getTransaction().begin();
em.persist(d);
em.getTransaction().commit();
on committing the following statements are generated...
Hibernate: insert into DEPARTMENT (DEPARTMENT_NAME, LOCATION, DEPARTMENT_ID) values (?, ?, ?)
Hibernate: insert into EMPLOYEE (EMPLOYEE_NAME, EMPLOYEE_ID) values (?, ?)
Hibernate: insert into EMPLOYEE (EMPLOYEE_NAME, EMPLOYEE_ID) values (?, ?)
**Hibernate: update EMPLOYEE set DEPARTMENT_ID=? where EMPLOYEE_ID=?
**Hibernate: update EMPLOYEE set DEPARTMENT_ID=? where EMPLOYEE_ID=?
my question here is why 2 extra update(marked by *) statements are needed?
That's the order on which Hibernate does the operations normally. Take a look at this
https://docs.jboss.org/hibernate/orm/4.2/javadocs/org/hibernate/event/internal/AbstractFlushingEventListener.html#performExecutions%28org.hibernate.event.spi.EventSource%29
According to this documentation:
Execute all SQL (and second-level cache updates) in a special order so
that foreign-key constraints cannot be violated:
When you add Employees to a Department, employees must have a Department ID so that's the reason why Hibernate do an extra update.
If you want to avoid it you can create first the department, and then the employees adding manually Department id
Due to the #OneToMany #JoinColumn(name = "DEPARTMENT_ID") that annotates the attribute Department.employees the table
EMPLOYEE has a foreign key to the table DEPARTMENT. When you persiste the new department with the two employees a new row is inserted into the table DEPARTMENT and two rows are inserted into the table EMPLOYEE but the column DEPARTMENT_ID is null. Then two updates are executed to set this column and relate the EMPLOYEE rows with the DEPARTMENT row.
The question is why this is not done in one step, i.e. instead of executing the following:
Hibernate: insert into DEPARTMENT (DEPARTMENT_NAME, LOCATION, DEPARTMENT_ID) values (?, ?, ?)
Hibernate: insert into EMPLOYEE (EMPLOYEE_NAME, EMPLOYEE_ID) values (?, ?)
Hibernate: insert into EMPLOYEE (EMPLOYEE_NAME, EMPLOYEE_ID) values (?, ?)
**Hibernate: update EMPLOYEE set DEPARTMENT_ID=? where EMPLOYEE_ID=?
**Hibernate: update EMPLOYEE set DEPARTMENT_ID=? where EMPLOYEE_ID=?
the following should be executed:
Hibernate: insert into DEPARTMENT (DEPARTMENT_NAME, LOCATION, DEPARTMENT_ID) values (?, ?, ?)
Hibernate: insert into EMPLOYEE (EMPLOYEE_NAME, EMPLOYEE_ID, DEPARTMENT_ID) values (?, ?, ?)
Hibernate: insert into EMPLOYEE (EMPLOYEE_NAME, EMPLOYEE_ID, DEPARTMENT_ID) values (?, ?, ?)
I have two simple tables Customers and Orders with relation oneToMany from customer to Orders table.
This is my Customers.java
#Entity
public class Customers implements Serializable {
#Id
#GeneratedValue
private int cID;
private String name;
private String email;
// getter and setters
}
And this is Orders.java:
#Entity
public class Orders implements Serializable {
#Id
#GeneratedValue
private int orderID;
private int cId;
#Column(nullable = false)
#Temporal(TemporalType.DATE)
private Date date;
#ManyToOne(cascade = CascadeType.ALL)
private Customers customers;
// getter and setters
}
Now, i am going to insert two record in Orders table:
public static void main(String[] args) {
SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
Orders orders1 = new Orders();
Orders orders2 = new Orders();
Customers customer = new Customers();
customer.setName("c1");
customer.setEmail("abc#gmail.com");
orders1.setDate(new Date());
orders2.setDate(new Date());
orders1.setCustomers(customer);
orders2.setCustomers(customer);
session.save(orders1);
session.save(orders2);
session.getTransaction().commit();
session.close();
sessionFactory.close();
}
This is the result in console:
Hibernate: alter table Orders drop foreign key FK_hmbx2rg9tsgqikb3kodqp90c4
Hibernate: drop table if exists Customers
Hibernate: drop table if exists Orders
Hibernate: create table Customers (cID integer not null auto_increment, email varchar(255), name varchar(255), primary key (cID))
Hibernate: create table Orders (orderID integer not null auto_increment, cId integer not null, date date not null, customers_cID integer, primary key (orderID))
Hibernate: alter table Orders add constraint FK_hmbx2rg9tsgqikb3kodqp90c4 foreign key (customers_cID) references Customers (cID)
Feb 24, 2015 1:58:52 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Hibernate: insert into Customers (email, name) values (?, ?)
Hibernate: insert into Orders (cId, customers_cID, date) values (?, ?, ?)
Hibernate: insert into Orders (cId, customers_cID, date) values (?, ?, ?)
And this is the result tables:
Why the cID in Orders table (which is a foreign key references to customers) is 0?
It should be 1.
It think in your orders table customers_cId is the actual foreign key reference column to the customers table. As you haven't gave any column name explicitly, it internally took column name as customers_cId by joining the variables from both the entities. customers from the orders and cId from the customers entity.
Just to verify you can try giving some other name using #JoinColumn annotation.
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name="order_cId")
private Customers customers;
And cId in orders table is just one more independent column, as you have not set any value to it, its taking the default value as 0. Try setting some random value to it.
For example, I have an account entity with two constructors.
#Entity
public class DefaultAccount implements Account {
#OneToOne(targetEntity = DefaultManager.class)
private Manager manager;
public DefaultAccount(String email, String password) {
this.email = email;
this.password = password;
}
public DefaultAccount(String email, String password, Manager manager) {
this(email, password);
this.manager = manager;
}
// Getters
}
The second constructor is used for assigning an account as manager. A manager can manage a set of accounts.
#Entity
public class DefaultManager implements Manager {
#OneToOne(targetEntity = DefaultAccount.class)
private Account managerAccount;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "manager", targetEntity = DefaultAccount.class)
private Set<Account> accountsToManage = new HashSet<Account>();
public DefaultManager(Account managerAccount, Set<Account> accountsToManage) {
this.managerAccount = managerAccount;
this.accountsToManage.addAll(accountsToManage);
}
// Getters
}
Will the above relationships work? If not, what's the best alternative to make it working?
Yes, it will work, you can see a SpringTest with hibernate here.
You need a constructor with no arguments to work with JPA, this constructor don't need to be public, it can be protected.
Also, your entities need a field annotated with #Id. If your interfaces provides a #Id getter method, you need to put your annotations (#OneToMany, etc), in the getters methods of your concrete classes.
If you execute the test, you will see the result:
Hibernate: call next value for man_seq
Hibernate: insert into Test25504340$DefaultAccount (manager_id, password, email) values (?, ?, ?)
Hibernate: insert into Test25504340$DefaultAccount (manager_id, password, email) values (?, ?, ?)
Hibernate: insert into Test25504340$DefaultAccount (manager_id, password, email) values (?, ?, ?)
Hibernate: insert into Test25504340$DefaultManager (managerAccount_email, id) values (?, ?)
Hibernate: update Test25504340$DefaultAccount set manager_id=?, password=? where email=?
Where:
First, get the sequence to insert the manager (I add a attribute Long id to DefaultManager).
It will add the three accounts referencing the Manager (Account#manager -> Manager#id).
Insert the Manager
Update the references of the Manager#Account to target the Account one (Manager#manageAccount -> Account#email).
You can change the order of the calls (persirst first the manager for example), and the result will be different sequence of inserts with the same final result.
I want to persist a mail entity which has some resources (inline or attachment). First I related them as a bidirectional relation:
#Entity
public class Mail extends BaseEntity {
#OneToMany(mappedBy = "mail", cascade = CascadeType.ALL, orphanRemoval = true)
private List<MailResource> resource;
private String receiver;
private String subject;
private String body;
#Temporal(TemporalType.TIMESTAMP)
private Date queued;
#Temporal(TemporalType.TIMESTAMP)
private Date sent;
public Mail(String receiver, String subject, String body) {
this.receiver = receiver;
this.subject = subject;
this.body = body;
this.queued = new Date();
this.resource = new ArrayList<>();
}
public void addResource(String name, MailResourceType type, byte[] content) {
resource.add(new MailResource(this, name, type, content));
}
}
#Entity
public class MailResource extends BaseEntity {
#ManyToOne(optional = false)
private Mail mail;
private String name;
private MailResourceType type;
private byte[] content;
}
And when I saved them:
Mail mail = new Mail("asdasd#asd.com", "Hi!", "...");
mail.addResource("image", MailResourceType.INLINE, someBytes);
mail.addResource("documentation.pdf", MailResourceType.ATTACHMENT, someOtherBytes);
mailRepository.save(mail);
Three inserts were executed:
INSERT INTO MAIL (ID, BODY, QUEUED, RECEIVER, SENT, SUBJECT) VALUES (?, ?, ?, ?, ?, ?)
INSERT INTO MAILRESOURCE (ID, CONTENT, NAME, TYPE, MAIL_ID) VALUES (?, ?, ?, ?, ?)
INSERT INTO MAILRESOURCE (ID, CONTENT, NAME, TYPE, MAIL_ID) VALUES (?, ?, ?, ?, ?)
Then I thought it would be better using only a OneToMany relation. No need to save which Mail is in every MailResource:
#Entity
public class Mail extends BaseEntity {
#OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
#JoinColumn(name = "mail_id")
private List<MailResource> resource;
...
public void addResource(String name, MailResourceType type, byte[] content) {
resource.add(new MailResource(name, type, content));
}
}
#Entity
public class MailResource extends BaseEntity {
private String name;
private MailResourceType type;
private byte[] content;
}
Generated tables are exactly the same (MailResource has a FK to Mail). The problem is the executed SQL:
INSERT INTO MAIL (ID, BODY, QUEUED, RECEIVER, SENT, SUBJECT) VALUES (?, ?, ?, ?, ?, ?)
INSERT INTO MAILRESOURCE (ID, CONTENT, NAME, TYPE) VALUES (?, ?, ?, ?)
INSERT INTO MAILRESOURCE (ID, CONTENT, NAME, TYPE) VALUES (?, ?, ?, ?)
UPDATE MAILRESOURCE SET mail_id = ? WHERE (ID = ?)
UPDATE MAILRESOURCE SET mail_id = ? WHERE (ID = ?)
Why this two updates? I'm using EclipseLink, will this behaviour be the same using another JPA provider as Hibernate? Which solution is better?
UPDATE:
- If I don't use #JoinColumn EclipseLink creates three tables: MAIL, MAILRESOURCE and MAIL_MAILRESOURCE. I think this is perfectly logic. But with #JoinColumn it has information enough for creating only two tables and, in my opinion, do only inserts, with no updates.
When you use a #JoinColumn in a OneToMany you are defining a "unidirectional" one to many, which is a new type of mapping added in JPA 2.0, this was not supported in JPA 1.0.
This is normally not the best way to define a OneToMany, a normal OneToMany is defined using a mappedBy and having a ManyToOne in the target object. Otherwise the target object has no knowledge of this foreign key, and thus the separate update for it.
You can also use a JoinTable instead of the JoinColumn (this is the default for OneToMany), and then there is no foreign key in the target to worry about.
There is also a fourth option. You could mark the MailResource as an Embeddable instead of Entity and use an ElementCollection.
See,
http://en.wikibooks.org/wiki/Java_Persistence/OneToMany
Mapped by defines owning side of the relation ship so for JPA it gives better way to handle associations. Join Column only defines the relationship column. Since JPA is completely reflection based framework I could think of the optimization done for Mapped by since it is easy find owning side this way.