java - EclipseLink 是否有类似 Hibernate Interceptors 的功能?
问题描述
找到了一种在 JPA 中使用 Hibernate 拦截器将枚举用作具有自己表的实体的方法。例如,我想用作枚举后面的实体:
@Entity
public enum Color {
RED(255, 0, 0),
GREEN(0, 255, 0),
BLUE(0, 0, 255)
@Id
public final byte id = (byte)ordinal();
@Column(unique = true, nullable = false)
public final String name = name();
@Column(nullable = false)
public final int red;
@Column(nullable = false)
public final int green;
@Column(nullable = false)
public final int blue;
}
为了使 JPA 正确地与该实体一起工作,我们可以编写以下拦截器,它将枚举转换为它的序号以保存在数据库中:
public class EnumAsEntityInterceptor extends EmptyInterceptor {
@Override
public Object instantiate(String entityName, EntityMode entityMode, Serializable id) {
try {
Object o;
Class cls = Class.forName(entityName);
if (cls.isEnum() && id instanceof Number) {
o = cls.getEnumConstants()[((Number)id).intValue()];
} else {
o = super.getEntity(entityName, id);
}
return o;
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
}
启用此拦截器后,我们可以使用枚举实体:
entityManager.merge(Color.RED);
但是这个解决方案只适用于 Hibernate。有没有办法用 EclipseLink 做类似的事情?经过一番研究,我没有发现 EclipseLink 中有任何功能可以做到这一点。
解决方案
推荐阅读
- django - POSTMAN Curd 基于类的视图
- python - Python平衡分区问题,返回子组之间的最小总和被忽略的测试用例
- python - 如何使用 sqlalchemy 在 Python 运行时打印出 TLS 版本?
- javascript - 使用 socket.io 和 React 获取数据的正确方法是什么?
- loops - 如何在 for 循环的每次迭代中保存变量
- c++ - 是否使用对使用 reinterpret_cast 未定义行为强制转换的指针的引用?
- python - 蟒蛇 | Flask Url_For MissingSchema:无效的 URL 错误
- angular - 有没有办法自动更新和构建一个android应用程序
- hibernate - jBPM在计时器事件后创建重复任务:多个实例正在运行
- python - 通过 dj_rest_auth 在用户注册中保存额外的字段