I'm trying to get a Many to Many relationship with additional data to work using annotations. I've read that this is done using a couple of OneToMany (or the inverse, 2 ManyToOne) relationships with an intermediate Entity.The approach actually works, but I haven't been able to do it without having to set an Id on the association table. What I want to do is use the combination of the 2 foreign keys from the associated tables as the parent key for the entity, and avoid using an unnecesary Id in the relationship entity.
An example would be:
Users {user_id, ...}
Messages {message_id, ...}
and the relationship I want to create is such that many users can receive multiple messages, and set an additional status field in that relationship:
ReceivedMessages {user_id, message_id, status}
My code for the association entity is:
Code:
package ejb;
import javax.persistence.*;
import java.io.Serializable;
@Entity
@Table(name = "message_recipients")
public class MessageRecipient implements Serializable {
private Long id;
private Message message
private User recipient;
private Integer status;
public MessageRecipient() {
}
@Id(generate = GeneratorType.AUTO)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@ManyToOne
@JoinColumn(name = "message_id")
public Message getMessage {
return message;
}
public void setMessage(Message message) {
this.message = message;
}
@ManyToOne
@JoinColumn(name = "recipient_id")
public User getRecipient() {
return recipient;
}
public void setRecipient(User recipient) {
this.recipient = recipient;
}
@Column(name = "status")
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
}
If I try the same code without setting the Id field and @Id annotation, it fails.Does anyone know how to avoid using the id and/or how to set the user_id - message_id pair to be unique via annotations?