我有一些通过数据库持久化的作业控制。
有一个动作界面:
public interface IAction {
Object perform(Work work, Map<String, String> parameter) throws Exception;
}
有多种实施方式:
public class SingleFileConvertAction implements IAction {
public InputStream perform(Work work, Map<String, String> parameter) throws Exception {
// ...
}
}
public class CacheDeleteAction implements IAction {
public Object perform(Work work, Map<String, String> parameter) throws Exception {
// ...
}
}
// ...
有一个工作控制类:
@Entity
public class ActionControl {
@Id
@GeneratedValue
private Integer id;
@ElementCollection
private Map<String, String> parameter = new HashMap<String, String>();
@ManyToOne
@JoinColumn(name = "work_id", referencedColumnName = "id", nullable = false)
private Work work;
private IAction action;
private Date requestTime;
private Date startTime;
private Date endTime;
// ...
private ActionControl() {}
public ActionControl(Work work, String action, Map<String, String> parameter) {
this.parameter = parameter;
this.work = work;
// ...
}
}
现在我想将动作控件保存到数据库中。我只需要知道,使用哪个动作类。其他所有内容都保存在work
和parameter
中。
我考虑过保存字符串并执行switch()来选择它"CacheDeleteAction" -> CacheDeleteAction
,但我认为有更好的方法可以做到。是否可以保存&#34; CacheDeleteAction.class&#34;在数据库字段中? (我在Spring注释中看到了它)
如何在数据库中保存对java类的引用?
答案 0 :(得分:0)
正如@XtremeBaumer所说,取决于你的用法,如果你需要稍后创建一个实例,那么XtremeBaumer所建议的将是首选的方式,否则使用枚举它将会是这样的,
public enum IActionEnum {
CACHE_DELETE_ACTION("Cache delete action"),
SINGLE_FILE_CONVERT_ACTION("Single file convert action"),
private String actionDescription;
IActionEnum(String description) {
actionDescription= description;
}
@Override
public String toString() {
return actionDescription;
}
}
无论何时您想将其保存到DB,您都可以使用它,
IAction actionControl = new IAction();
// set all other parameters
actionControl.setIAction(IActionEnum.CACHE_DELETE_ACTION)
actionControlRepository.save(actionControl);