[英]Hibernate annotation to a transient collection field
我希望使用收集字段來查詢,但是我找不到解決方法。 有一個@Formula
批注,但不適用於集合。 您可能會問,為什么我不使用@ManyToMany
或類似的注釋。 問題是,我有一個表(例如,稱為“關系”),其中的列與此類似:
ID | ChildType | ChildID | ParentType | ParentID |
現在,ChildType和ParentType可以是我的應用程序中許多類之一,因此我不能(我不想)使用@ManyToMany
映射,因為它將為每個類創建另一個表。 我想要的是在類A中有一個稱為“關系”的收集字段,該字段將從“關系”表中選擇所有行(“關系”), where ChildID = A.id and ChildType = 'A'
。 那可能嗎?
更新:看來我還不夠清楚。 好吧,說,我有一個類Relationship,其中ParentType
和ChildType
只是作為字符串的parent和child的類名稱:
@Entity
public class Relationship {
@Id
@GeneratedValue
private Long id;
@Enumerated(EnumType.STRING)
private ParentType parentType;
private Long parentId;
@Enumerated(EnumType.STRING)
private ParentType childType;
private Long childId;
}
然后,我有各種具有字段relationships
的類,例如:
@Entity
public class A {
@Id
@GeneratedValue
private Long id;
private Set<Relationship> relationships = new HashSet<Relationship>();
}
@Entity
public class B {
@Id
@GeneratedValue
private Long id;
private Set<Relationship> relationships = new HashSet<Relationship>();
}
@Entity
public class C {
@Id
@GeneratedValue
private Long id;
private Set<Relationship> relationships = new HashSet<Relationship>();
}
現在,我希望Hibernate每當獲得對應類的實例bean時,就可以查詢Relationships
表來查找每個類A
, B
和C
的關系。 像這樣:
@Query("(select relationship from Relationship relationship where relationship.childId = id and relationship.childType = 'A')")
private Set<Relationship> relationships = new ArrayList<Relationship>();
考慮Relation_ship是您的Relationship表,而上述表是parent_child
SQLQuery query = session.createSQLQuery(
"SELECT r
FROM relation_ship r
INNER JOIN
parent_child p
ON r.id = p.ChildID and
p.ChildType := ChildType").setParameter("ChildType","A");
List<Relationship> = query.list();
我現在做了一個解決方法,但是我仍然想知道是否有一種方法可以在我的Entity類中添加注釋。
解決方法如下:在Relationship的存儲庫界面中添加一個方法,該方法擴展了JpaRepository
。
public List<Relationship> findByChildIdAndChildType(Long childId,
String childType);
然后,在A,B,C實體的每個服務類中,添加關系資源,並通過添加設置關系字段的代碼來編輯find
和findAll
或任何方法。
@Service
@Transactional
public class AService implements IAService {
@Resource
private IARepository aRepository;
@Resource
IRelationshipRepository relationshipRepository;
@Override
public A findOne(Long id) {
A a = aRepository.findOne(id);
List<Relationship> relationships = new ArrayList<Relationship>();
relationships =
relationshipRepository.findByChildIdAndChildType(id, 'A');
a.setRelationships(relationships);
return a;
}
// other fields and methods omitted..
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.