开发者

Hibernate "JOIN ... ON"?

I have an application that uses Hibernate for its domain objects. One part of the app is common between a few apps, and it has no knowledge of the other systems. In order to handle relations, our class looks like this:

@Entity
public class SystemEvent {
   @Id @GeneratedValue
   public int entity_id;

   @Column(name="event_type")
   public String eventType;

   @Column(name="related_id")
   public int relatedObjectId;
}

relatedObjectId holds a foreign key to one of several different objects, depending on the type of event. When a system wants to know about events that are relevant to its interests, it grabs all the system events with eventType "NewAccounts" or some such thing, and it knows that all of those relatedObjectIds are IDs to a "User" object or similar.

Unfortunately, this has caused a problem down the line. I can't figure out a way to tell Hibernate about this mapping, which means that HQL queries can't do joins. I'd really like to create an HQL query that looks like this:

SELECT users FROM SystemEvent event join Users newUsers where event.eventType = 'SignUp'

However, Hibernate has no knowledge of the relationsh开发者_运维百科ip between SystemEvent and Users, and as far as I can tell, there's no way to tell it.

So here's my question: Is there any way to tell Hibernate about a relationship when your domain objects reference each other via ID numbers and not class references?


First off, when you have an column with a name like 'eventType' you are talking about a discriminator column.

Secondly, a lot of the power/convenience that an ORM provides is the ability to interact with your Business Objects not your Database.

I would take a look at the Inheritance Chapter in the Hibernate docs.

If you can, I'd setup an abstract class called SystemEvent which, from your example above, would just have and ID. Each concrete implementation would contain the specific field/property to the 'relatedObject'. I typically use a 'table per class' or 'table per sub-class' mapping for this type of scenario.

@Entity
@Inheritance(strategy=InheritanceType.JOINED)
public abstract class SystemEvent {
   @Id @GeneratedValue
   public int eventId;
}

@Entity
@PrimaryKeyJoinColumn(name="event_id")
public class SignupEvent extends SystemEvent {
   @Column(name="user_id")
   public User user;
}

@Entity
@PrimaryKeyJoinColumn(name="event_id")
public class OtherEvent extends SystemEvent {
   @Column(name="other_id")
   public OtherAssociatedObject otherAssociatedObject;
}

You would modify your HQL to look like this:

SELECT users FROM SignupEvent event join Users newUsers

Let me know if you want me to clarify any part of this answer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜