我有两张桌子:Word和Stems。第二个字段是Word的外键字段。如此多的词干可以属于一个词。
在Java中,我创建了实体Word和Stem。因为单词可以有很多词干,并且我在这个词干列表上有一些操作,所以我决定将这个列表与相应的方法放在一个名为Stems的单独的类中。此类的对象在Word实体中。下面我将介绍我的代码如何:
Word.java
@Entity
@Table(name = "Word")
@Inheritance(strategy=InheritanceType.JOINED)
public abstract class Word implements Serializable{
// primary key and other columns
@Transient
protected Stems stems = new Stems();
public void setStems(List<Stem> stems) {
this.stems.setStems(stems);
}
@OneToMany(cascade=CascadeType.ALL, fetch = FetchType.EAGER, mappedBy="word")
public List<Stem> getStems() {
return stems.getStems();
}
}
Stems.java
public class Stems {
private List<Stem> stems = new ArrayList<>();
public List<Stem> getStems() {
return stems;
}
public void setStems(List<Stem> stems) {
this.stems = stems;
}
}
Stem.java
@Entity
@Table(name = "Stems")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="Type",discriminatorType=DiscriminatorType.STRING)
public abstract class Stem implements Cloneable{
@Id
@Column(name = "Stem", unique = true, nullable = false, length = 64)
private String rawStem;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "WordId", nullable = false)
private Word word;
}
这是我的问题。是否可以通过HQL查询来获取具有正确词干的单词?如果没有那么如何实现这一点。也许这个结构不允许工作?如何使用词干添加/更新单词?我尝试在每个词干中使用单词和单词id设置词干数组,然后使用session.merge(单词)但它不起作用。
答案 0 :(得分:0)
请在 @OneToMany 注释中注释注释 @Embedded , @Embeddable 和参数 orphanRemoval 。
<强> Word.java 强>
@Entity
@Table(name = "Word")
@Inheritance(strategy=InheritanceType.JOINED)
public abstract class Word implements Serializable{
// primary key and other columns
@Embedded
protected Stems stems = new Stems();
public List<Stem> getStems() {
return stems.getStems();
}
public void setStems(List<Stem> stems) {
this.stems.setStems(stems);
}
}
<强> Stems.java 强>
@Embeddable
public class Stems {
// orphanRemoval removes stems which is present in database but not on list
@OneToMany(cascade=CascadeType.ALL, fetch = FetchType.EAGER, mappedBy="word", orphanRemoval = true)
private List<Stem> stems = new ArrayList<>();
// getters/setters
}
Stem.java - 没有变化。