如何解决(Java + Spring + JPA + Hibernate Mappings)关系

时间:2019-02-11 16:49:09

标签: java hibernate jpa

我已经阅读了许多有关使用JPA + Hibernate进行映射的主题,但是尝试了几件事之后我无法获得预期的结果。

我已经声明了我所有的单向关系,因为我认为不需要双向关联

我要映射的对象是: 客户有一个国家和一个地址列表。

@Table(name = "Client")
@Entity
public class Client
{
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO, generator = "native")
    @GenericGenerator(name = "native", strategy = "native")
    private Long id;

    @OneToOne(cascade = { CascadeType.MERGE, CascadeType.PERSIST })
    @JoinColumn(name="country_id", unique = false, /*nullable = false,*/ insertable = true, updatable = false, foreignKey = @ForeignKey(name = "country_fk0"))
    private Country country;

    @OneToMany(cascade = { CascadeType.PERSIST }, orphanRemoval = true)
    @JoinColumn(name = "address_id",/* nullable = false,*/ foreignKey = @ForeignKey(name = "address_fk0"))
    private List<Address> address;

//GETTERS / SETTERS
}

然后,我将评估客户端并将其保存在新的ClientProcessed表中,该表将引用存储在“客户端对象”中的“地址”和“国家/地区”对象。

@Table(name = "ProcessedClient")
@Entity
public class ProcessedClient
{
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO, generator = "native")
    @GenericGenerator(name = "native", strategy = "native")
    private Long id;

    @OneToOne(cascade = { CascadeType.MERGE, CascadeType.PERSIST })
    @JoinColumn(name="client_evaluation_id", unique = false, /*nullable = false,*/ insertable = true, updatable = false, foreignKey = @ForeignKey(name = "evaluation_fk0"))
    private ClientEvaluation evaluation;

    @OneToOne(cascade = { CascadeType.MERGE })
    @JoinColumn(name="country_id", unique = false, /*nullable = false,*/, foreignKey = @ForeignKey(name = "country_fk1"))
    private Country country;

    @OneToMany(cascade = { CascadeType.MERGE}, orphanRemoval = true)
    @JoinColumn(name = "address_id",/* nullable = false,*/ foreignKey = @ForeignKey(name = "address_fk2"))
    private List<Address> addresses;

//GETTERS / SETTERS
}

那么当我这样做时:

Country country = new Country();
country.setId(1l); // (DB ID)

// I do the same with addresses

ProcessedClient processedClient = new ProcessedClient();
processedClient.setAddresses(addresses);
processedClient.setCountry(country);

this.getDao().save(processedClient);

结果:

  

org.hibernate.TransientPropertyValueException:对象引用了   未保存的临时实例-在保存临时实例之前   冲洗

Thx

1 个答案:

答案 0 :(得分:0)

摘自文档:

Hibernate定义并支持以下对象状态:

  • Transient-如果对象刚刚使用new运算符实例化,并且与Hibernate Session不相关,则该对象为瞬态。 ...
  • 持久-持久实例在数据库中具有表示形式和标识符值。

您应按ID从数据库加载国家/地区,然后将其设置为ProcessedClient。