在数据库中存储对java类的引用
我有一些通过数据库持久化的作业控制 有一个操作界面:在数据库中存储对java类的引用,java,spring,spring-data-jpa,Java,Spring,Spring Data Jpa,我有一些通过数据库持久化的作业控制 有一个操作界面: public interface IAction { Object perform(Work work, Map<String, String> parameter) throws Exception; } 公共接口接口接口{ 对象执行(工作、映射参数)引发异常; } 有多种实现方式: public class SingleFileConvertAction implements IAction { publi
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 {
// ...
}
}
// ...
公共类SingleFileConvertAction实现IAAction{
公共InputStream执行(工时,映射参数)引发异常{
// ...
}
}
公共类CacheDeleteAction实现IAAction{
公共对象执行(工时、映射参数)引发异常{
// ...
}
}
// ...
有一个作业控制类:
@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;
// ...
}
}
@实体
公共类动作控制{
@身份证
@生成值
私有整数id;
@元素集合
私有映射参数=new HashMap();
@许多酮
@JoinColumn(name=“work\u id”,referencedColumnName=“id”,nullable=false)
私人工作;
私人诉讼;
私人日期和时间;
私人约会开始时间;
私人日期结束时间;
// ...
私有ActionControl(){}
公共ActionControl(工时、字符串操作、映射参数){
this.parameter=参数;
这个。工作=工作;
// ...
}
}
现在我想将动作控件保存到数据库中。我只需要知道,该使用哪个动作类。其他所有内容都保存在工作
和参数
中
我考虑过保存一个字符串并使用switch()来选择它,就像“CacheDeleteAction”->CacheDeleteAction
一样,但我认为有更好的方法。是否可以在数据库字段中保存“CacheDeleteAction.class”?(我在春天的注解中看到)
如何在数据库中保存对java类的引用?正如@XtremeBaumer所说,这取决于您的使用情况,如果您以后需要创建一个实例,那么XtremeBaumer建议的方法将是首选方法,否则使用enum时,它将是这样的
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);
您的
ActionControl
类中似乎没有IAction
。对吗?对。我在考虑这个问题。但我可以补充一点,如果这能让人更好理解的话。这只是为了让结构更清晰,让我的问题更容易理解。为actionsOK创建一个枚举如何,但最终还是会使用switch(),对吗?我认为可能会有一个自动映射,就像它对其他数据类型所做的那样。这取决于您将来对该字段的使用情况。我认为字符串甚至可能比枚举更好,因为您可以使用Class.forName(“classname with package”)
获得正确的类,甚至可能获得实例。