【问题标题】:Map primary key to composite key in JPA将主键映射到 JPA 中的复合键
【发布时间】:2020-10-04 17:00:51
【问题描述】:

我有 2 个表,即 user 和 user_session。

用户表有 user_id 作为主键,它是 user_session 表的引用者。

加上 user_session 有复合键,包括 session_intime 和 user_id。

我在 JPA 中设计了我的实体。现在我想映射这两个实体。我试图映射这两个表。但是我的应用程序构建失败了。你能帮帮我吗?

@Entity
@Table(name="user")
public class User {
    @Id
    @Email
    @Column(name = "user_id")
    private String userId;

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

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

    @OneToMany(fetch = FetchType.LAZY)
    @JoinColumn(name = "userId", referencedColumnName = "user_id")
    private UserSession userSession;
}

@Entity
@Table(name="user_session")
public class UserSession{
    @EmbeddedId
    private UserSessionPK userSessionPK;

    @Column(name = "remote_ip")
    private String remoteIp;
}

@Embeddable
public class UserSessionPK implements Serializable {
    private static final long serialVersionUID = 1L;

    @Column(name = "user_id")
    private String userId;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "time_in")
    private Date timeIn;
}

我想将 User 表的 user_id 映射到 UserSessionPK 的 user_id。我是 JPA 新手,所以我不知道如何使用可嵌入类进行映射。

【问题讨论】:

  • 你能发布整个堆栈跟踪吗?
  • org.springframework.beans.factory.BeanCreationException:在类路径资源 [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class] 中定义名称为“entityManagerFactory”的 bean 创建错误:调用初始化方法失败;嵌套异常是 org.hibernate.AnnotationException: Referenced property not a (One|Many)ToOne: com.recruitment.model.login.UserSession.userSessionPK.userId in mappedBy of com.recruitment.model.login.User.userSession
  • 我刚刚在用户表中添加了映射,这给了我这个错误

标签: spring-boot hibernate spring-data-jpa hibernate-mapping


【解决方案1】:

删除 mappedBy 属性。当您有双向关系时使用此属性来指示关系的哪一方是所有者。

但是你需要设置外键也就是 JoinColumn

@JoinColumn("user_id")
@OneToMany(fetch = FetchType.LAZY)
private UserSession userSession;

【讨论】:

  • 你说的我已经试过了。应用程序成功运行,但现在抛出错误,原因是:java.sql.SQLSyntaxErrorException: Unknown column 'user0_.user_session_time_in' in 'field list'
  • 哦,对不起!我更新了我的答案。你需要@JoinColumn
  • 无法构建 Hibernate SessionFactory;嵌套异常是 org.hibernate.MappingException:损坏的列映射:userSession.id of:com.recruitment.model.login.User
  • 嗯。问题是关系 User -> UserSession 不是 OneToOne 它是 OneToMany。对吗?
  • 是的。一个用户可以通过多个会话多次登录。
猜你喜欢
  • 2019-04-22
  • 1970-01-01
  • 2018-11-28
  • 2018-05-08
  • 2017-01-30
  • 2017-08-06
  • 1970-01-01
  • 1970-01-01
  • 2017-02-21
相关资源
最近更新 更多