[英]hibernate - Persisting a composition interface of strategy pattern
我有以下类结构:
public abstract class Creature{
private String name;
//strategy pattern composition
private SkillInterface skill;
}
public interface SkillInterface {
void attack();
}
public class NoSkill implements SkillInterface {
@Override
public void attack() {
//statements
}
}
我的目标是将Creature对象持久保存在数据库中的一个表中。 SkillInterface的子类没有任何字段。 当他们确定行为时,我想将选定的SkillInterface类名转换为String,因为我只需要保持生物当前技能策略的类名,使用像skill.getClass()。getSimpleName()这样的字符串。 我尝试用@Converter注释实现它,使用AttributeConverter类将SkillInterface转换为String并保存,但始终有映射异常。 我希望能够将其保存为String并检索为SkillInterface对象。
但是如何用Hibernate实现呢? 或者我有设计错误?
好吧,我发现我已经找到了一个可用于持久化策略模式接口实现的基本解决方案。 我使用@Converter注释和AttributeConverter类将策略类名转换为列,同时保存到数据库并将检索到的String转换回策略类,如下所示:
@Entity
public class Creature {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@Convert(converter = SkillConverter.class)
private SkillInterface skill;
}
public class SkillConverter implements AttributeConverter<SkillInterface,String> {
@Override
public String convertToDatabaseColumn(SkillInterface skill) {
return skill.getClass().getSimpleName().toLowerCase();
}
@Override
public SkillInterface convertToEntityAttribute(String dbData) {
//works as a factory
if (dbData.equals("noskill")) {
return new NoSkill();
} else if (dbData.equals("axe")) {
return new Axe();
}
return null;
}
}
public interface SkillInterface {
public String getSkill();
void attack();
}
public class NoSkill implements SkillInterface{
public String getSkill() {
return getClass().getSimpleName();
}
@Override
public void attack() {
//strategy statements
}
}
您可以在下面使用代理字段:
abstract class Creature {
@Column
private String name;
// strategy pattern composition
private SkillInterface skill;
@Column
private String skillName;
public String getSkillName() {
return skill.getClass().getSimpleName();
}
public void setSkillName(String skillName) {
//ignore
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.