将Hibernate中的值保存到实体表之外的另一个表中

时间:2017-10-12 08:12:32

标签: postgresql hibernate spring-boot

我有两张表bo_operatorhist_bo_operator_password。在bo_operator中,id列是hist_bo_operator_password的外键,operator_id中的hist_bo_operator_password可以与id中的bo_operator相同,@Entity @Table(name="bo_operator") public class Operator implements Serializable 中只有一个hist_bo_operator_password {1}}。

我的实体:

@ElementCollection
@CollectionTable(name="hist_bo_operator_password", joinColumns=@JoinColumn(name="id_operator"))
@Column(name="password")
public List<String> oldPasswords = new ArrayList<String>();

这就是我从@ElementCollection @CollectionTable(name="hist_bo_operator_password", joinColumns=@JoinColumn(name="id_operator")) @Column(name="password") public String oldPassword; 获取价值的方式:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: Illegal attempt to map a non collection as a @OneToMany, @ManyToMany or @CollectionOfElements: local.vlex.operator.model.Operator.oldPassword

但是当我试图通过以下方式获得一个值时:

hist_bo_operator_password

我收到错误:

operator.setOldPassword(oldPassword);

我想做的就是插入id @Table(name="bo_operator") @SecondaryTable(name = "hist_bo_operator_password",pkJoinColumns=@PrimaryKeyJoinColumn(name="id_operator", referencedColumnName="id")) 。我认为问题是,如果同一个@Column(name="password", table="hist_bo_operator_password") @OrderBy("data_ins") public String oldPassword; 有很多值,它就不知道使用哪个密码。 如何实现它?

@Edit 我也尝试过:

org.hibernate.HibernateException: Duplicate identifier in table for: [local.vlex.operator.model.Operator#1]

我甚至发现了ORDER BY:

:valid

但似乎在JPA中没有@Limit或类似的东西,我仍然有许多值导致错误的同一个id:

:invalid

2 个答案:

答案 0 :(得分:1)

为什么不创建hist_bo_operator_password的实体? 然后你可以拥有那些实体的List(而不仅仅是String List),只需将另一个对象添加到List并保存实体Operator。

答案 1 :(得分:1)

正如你在第一句中描述的那样,你有一对多的关系

@ElementCollection
@CollectionTable(name="hist_bo_operator_password", joinColumns=@JoinColumn(name="id_operator"))
@Column(name="password")
@OrderBy("data_ins")
public List<String> oldPasswords = new ArrayList<String>();

然后添加必要的getter

Optional<String> getPassword() {
    return oldPasswords.size() > 0
        ? Optional.of(oldPasswords.get(0))
        : Optional.empty();
}

和setter

void setPassword(String password) { // or maybe addPassword?
    oldPasswords.add(password);
}