休眠与主值一对一保存

时间:2019-05-06 18:06:00

标签: java hibernate

想要与主值一对一保存,如下所示。 有一个包含城市类别一对一的地址类别。 但是city是我的主要值,保存地址时我不想更新。只需从UI的下拉列表中选择城市,然后将对象设置为要寻址并保存地址即可。但是在保存时会出现以下错误。

org.hibernate.TransientPropertyValueException:对象引用了一个未保存的瞬态实例-在刷新之前保存该瞬态实例:com.app.fd.entity.Address.city-> com.app.fd.entity.City

@Entity
public class Address extends BaseEntity implements Serializable {
/**
 * 
 */
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "CONTACT_SEQ_GEN")
@SequenceGenerator(name="CONTACT_SEQ_GEN", sequenceName = "CONTACT_SEQ", allocationSize=5)
@Column(name = "id", updatable = false, nullable = false)
private Long id;

@Size(max = 50)
@NotNull
private String address1;

@Size(max = 50)
private String address2;

@Size(max = 15)
@NotNull
private String state;

@Size(max = 10)
@NotNull
private String pin;

@Size(max = 255)
private String landmark;

private Boolean deleted;

@OneToOne()
@JoinColumn(name = "city_id", insertable=false,updatable=false)
private City city;

}


@Entity
public class City {

/**
 * 
 */

private static final long serialVersionUID = 1L;


@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;

@Size(max = 30)
@Column(name = "name",unique = true)
private String name;

@Size(max = 5)
@Column(name = "code",unique = true)
private String code;
}




repository.save(address); // TransientPropertyValueException error

1 个答案:

答案 0 :(得分:0)

您收到此错误,是因为您将Address实体保存为未保存/分离的City实体。要解决此问题,您可以使用cascadeType.ALL,但是在您的情况下,您不想修改城市对象。您可以使用以下方法。

City cityFromUI = new City();
cityFromUI.setId(id); //get this id from UI. Store city dropdown as key = id and value = cityName
Address myNewAddress = new Address();
myNewAddress.set*()//Set other address fields
myNewAddress.setCity(cityFromUI);
repository.save(address);

使用上述代码,您的地址将被映射到相应的城市,并且您的城市将不会按照您在updatable实体中将false定义为Address的情况进行更新。