類別中,如果一個一對多關係設置爲急於rideSingle始終保存多次進入分貝連接對象兩次到表:休眠:保存當與eagerloaded一對多
其中被保存的類
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class RideSingle extends HibernateBasicClass{
@OneToMany(mappedBy = "rideSingle", fetch = FetchType.EAGER)
@Cascade(CascadeType.ALL)
protected List<TimedRouteLocation> route;
}
的refered類:
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class TimedRouteLocation extends HibernateBasicClass {
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(nullable = false)
protected RideSingle rideSingle;
}
休眠基類
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class HibernateBasicClass implements Serializable {
private static final long serialVersionUID = -2253382207065396453L;
@Id
@SequenceGenerator(name = "generator", allocationSize = 1, initialValue = 1)
@GeneratedValue(strategy = GenerationType.TABLE, generator = "generator")
@JsonProperty
private Long id;
@Column(nullable = false)
@Temporal(TemporalType.TIMESTAMP)
private Date createdOn = new Date();
@Version
private Date lastModified;
public HibernateBasicClass() {
super();
}
public Long getId() {
return id;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final HibernateBasicClass objWId = (HibernateBasicClass) obj;
// same id instance
if (getId() == objWId.getId())
;
// same id content
if (getId() != null) {
return getId().equals(objWId.getId());
} else {
return false;
}
}
}
只有一個變量,然後由
int i = rideSingleDaox.findAll().size(); // i is 0
rideSingleDao.saveOrUpdate(this);
i = rideSingleDaox.findAll().size(); // i is 2
的道看起來像這樣保存的:
public T saveOrUpdate(T object) {
getSession().saveOrUpdate(object);
return object;
}
如果rideSingle.route有2種元素 - > rideSingle在兩次放分貝。如果路線有3個元素,則將3個rideSingle放入數據庫中...
如果rideSingle加載路由懶惰,則不會出現此問題。
@Entity
public class RideSingle {
@OneToMany(mappedBy = "rideSingle", fetch = FetchType.EAGER)
@Cascade(CascadeType.ALL)
protected List<TimedRouteLocation> route;
}
有人知道爲什麼這是這種情況,我該如何解決它?
非常感謝!
請'@ Id'定義和代碼摘錄導致多個記錄被保存延長你的例子。 – MaDa
在實體被保存兩次的示例中:home中的RideSingle和TimedRouteLocation的實例存在於具體的關聯關係中,總共有多少個實例? – Ralph
@Mada我加了excerts。這有幫助嗎? –