w32*_*oom 4 java database-design design-patterns hibernate relational-database
我有以下类结构:
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
}
}
Run Code Online (Sandbox Code Playgroud)
我的目标是将 Creature 对象保存在数据库的一张表中。SkillInterface 的子类没有任何字段。当他们确定行为时,我想将选定的 SkillInterface 类名转换为字符串,因为我只需要使用诸如 Skill.getClass().getSimpleName() 这样的字符串来保留生物当前技能策略的类名。我尝试用@Converter注解来实现它,使用AttributeConverter类将SkillInterface转换为String并保存,但总是出现映射异常。我希望能够将其保存为字符串并检索为 SkillInterface 对象。
但如何用 Hibernate 来实现呢?还是我有设计错误?
好吧,看起来我已经找到了一个基本的解决方案,可用于持久化策略模式接口实现。我使用 @Converter 注释和 AttributeConverter 类将策略类名称转换为列,同时保存到数据库并将检索到的字符串转换回策略类,如下所示:
@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
}
}
Run Code Online (Sandbox Code Playgroud)