简体   繁体   中英

Hibernate: Using part of composite FK in another entity PK

im relative new to Hibernate Mappings im trying to achieve this functionality between the class Post and Comentario without luck

Relational model

@Embeddable
public class PostPK implements Serializable {

@Column(name="idPost")
private int postID;

@Column(name="idUsuario")
private int userIDFK;
-------------------------------
@Entity
@Table(name="Post")
public class Post {

@EmbeddedId
private PostPK id;

@ManyToOne
@MapsId(value="userIDFK")
@JoinColumn(name="idUsuario")
private Usuario usuario;

@OneToMany(mappedBy="post")
private List<Comentario> comentarios;

@Column(name="titulo")
private String titulo;

-----------------------------------
@Embeddable
public class ComentarioPK implements Serializable{

@Column(name="idComentario")
private int comentarioId;

@Column(name="idPost")
private int postIdFK;

---------------------------
@Entity
@Table(name="Comentario")
public class Comentario {

@EmbeddedId
private ComentarioPK id;

@ManyToOne
@MapsId("postIdFK")
@JoinColumn(name="idPost",referencedColumnName="idPost")
private Post post;

@Column(name="texto")
private String texto;

without mapping comentario and its fields in Post its working fine but when i decide to map it i get this error Unable to find column reference in the @MapsId mapping: idUsuario

is it not finding the idUsuario column in Comentario table? i dont want to add it , i can achieve joins in mysql but i dont know how to do it in Hibernate

@MapsId annotation is used to map the primary key fields of the parent entity with the child entity(with the same name). In your case your are having composite primary key in your parent entity but in child entity you want to refer only one field of it. PostPK has two fields : idPost and idUsuario . But in Comentario class when your are specifying ManyToOne relationship you are mentioning single column in @JoinColumn (which is idPost) and no field for idUsuario is available in your mapping. But as per the behavior of @MapsId annotation both the fields( idPost and idUsuario ) are expected in Comentario class.

Thus, in your case @MapsId annotation won't work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM