2013-08-26 27 views
2

我想要一个集合字段来使用查询,但我找不到一种方法来做到这一点。有一个@Formula注释,但不适用于集合。 您可能会问为什么我只是不使用@ManyToMany或类似的注释。关键是,我有一个表(比如,所谓的关系)的列与此类似:休眠注释到瞬态收集字段

ID | ChildType | ChildID | ParentType | ParentID |

现在,ChildType和ParentType的可以有很多类在我的应用程序之一,因此我不能(我不想)使用@ManyToMany映射,因为它会为每个类创建另一个表。我想要的是,在类A中有一个名为关系的集合字段,它将从关系表where ChildID = A.id and ChildType = 'A'中选择所有行(关系)。那可能吗?

更新:看起来我没有让自己清楚。好了,说,我有一个类关系,其中ParentTypeChildType是父母和孩子作为一个字符串只是类名:

@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查询Relationships表查找每个类,AB的关系,以及C每当我得到相应的类的实例豆。 事情是这样的:

@Query("(select relationship from Relationship relationship where relationship.childId = id and relationship.childType = 'A')") 
private Set<Relationship> relationships = new ArrayList<Relationship>(); 

回答

0

考虑relation_ship是你的关系表,并说明表上方是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(); 
+0

希望这会帮助你......如果不是,请用你的实体模型更新你的问题。 – Prabhakaran

+0

对不起,这不是我所要求的。我需要为我的字段(不是局部变量)注释,以便在获取实体类的实例bean时进行设置。我编辑了这个问题,我希望现在很清楚。 –

0

我做了一个解决方法了,但我还是想知道,如果有一种方法而是在我的实体类中添加注释。

解决方法如下: 在Relationship的储存库接口中添加一个方法,该方法扩展了JpaRepository

public List<Relationship> findByChildIdAndChildType(Long childId, 
    String childType); 

然后,在A,B,C实体每个服务种类,添加关系资源,并通过添加代码,设置关系字段中编辑findfindAll或任何方法。

@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.. 
}