我知道你可以用@Transient注释忽略字段。我找不到表示我不希望在数据库中保留特定子类的方法。这是模型类:
元素类:
@Entity
public class Element {
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
Long id;
@OneToMany(cascade = CascadeType.ALL)
private Map<String, Base> map;
private String text;
}
基类:
@Entity
@Inheritance(strategy= InheritanceType.JOINED)
public abstract class Base {
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
Long id;
String type;
}
Foo类:
@Entity
public class Foo extends Base {
boolean flag;
}
酒吧班:
@Entity
public class Bar extends Base {
int number;
}
测试对象保持不变:
Map<String, Base> map1 = new HashMap<>();
map1.put("foo-1" , new Foo());
map1.put("bar-1" , new Bar());
repo.save(new Element("element-1" , map1));
生成表格:
element table:
+------+-----------+
| id | text |
|------+-----------|
| 1 | element-1 |
+------+-----------+
element_map table;
+--------------+----------+-----------+
| element_id | map_id | map_key |
|--------------+----------+-----------|
| 1 | 1 | bar-1 |
| 1 | 2 | foo-1 |
+--------------+----------+-----------+
base table:
+------+--------+
| id | type |
|------+--------|
| 1 | <null> |
| 2 | <null> |
+------+--------+
foo table:
+--------+------+
| flag | id |
|--------+------|
| False | 2 |
+--------+------+
bar table:
+----------+------+
| number | id |
|----------+------|
| 0 | 1 |
+----------+------+
是否可以将JPA配置为忽略Bar类,而不是将其保留在DB中?
我尝试将@Transient注释添加到Bar
类中的所有字段,但最终生成的bar
表只生成了一个从id
类继承的字段Base
。我想避免使用无用的表数据库。
我尝试从Bar
类中删除@Entity注释,但每次持久存在Bar
对象时我都会遇到异常:
Caused by: org.springframework.orm.jpa.JpaSystemException: Unable to resolve entity name from Class [ch.smooth.hibernateinheritancehashmap.Bar] expected instance/subclass of [ch.smooth.hibernateinheritancehashmap.Base]; nested exception is org.hibernate.HibernateException: Unable to resolve entity name from Class [ch.smooth.hibernateinheritancehashmap.Bar] expected instance/subclass of [ch.smooth.hibernateinheritancehashmap.Base]
如何指定类层次结构的一部分是暂时的?
我已经在github上的一个小型spring-boot应用程序中隔离了问题以便更容易地再现:https://github.com/gladky/jpa-persistence-issue。运行mvn install会产生我提到的异常。