0

I'm using Hibernate 3.2.7.ga and I'm wondering if the following is possible.

Let's say there are 3 objects: Person, Town and Mayor.

When registering a Person in the application, you're asked to enter his or her town of residence. This field is saved as a String.

In another part of the application, you can register a Town (with it's name, number of inhabitants, etc.). After the Town is registered, you can add a Mayor to this town.

However, it is not desired to create a Town object for every town that is entered with a Client. An object is only desired when a Mayor needs to be registered.

I'm wondering if, just bij using the String field in Person, you can get the Mayor of the Town the Person lives in.

I'm thinking along these lines of code:

public class Client.java
{
  @Id
  public Long id;

  @Column(nullable = true, ??? )
  public String townOfResidence;

  public Mayor getMayor()
  {
    ...
  }
}

public class Town.java
{
  @Id
  public Long id;

  @Column(nullable = false, unique = true)
  public String name;

  @OneToOne
  public Mayor mayor;
}

I just tried thinking along the following lines:

@Transient
private Town townObject;

@ManyToOne(fetch = FetchType.LAZY, cascade = javax.persistence.CascadeType.ALL, targetEntity = Town.class, optional = true)
@JoinColumn(referencedColumnName = "town")
public Town getTown()
{
    return townObject;
}

4

2 回答 2

0

使用这种设计,您需要使用查询来获取此人所在城镇的市长:

select mayor from Town town
inner join town.mayor mayor
where town.name = :theTownOfResidenceOfTheClient

此查询必须作为 DAO/Repository 类的方法的一部分执行。市长不能在getMayor()Client 对象的方法中使用。

于 2012-09-04T09:22:56.703 回答
0

这更像是一个 ERD 问题而不是 ORM 问题。

要么你有和之间的关系PersonTown要么你没有。如果有,则只能选择引用表中键中的引用属性中的值,或者为 null(如果有效)。如果你没有关系,你就没有任何限制。

当然,您无需建立关系即可尝试在查询/JPQL 中混合它们。如果没有关系,您的程序可能会提供城镇的Town可能值列表Person,而不是强迫他们选择一个。或者你可以做类似的事情

 SELECT t FROM Town t WHERE t.name = ?

并通过那里的人镇。当然,也没有安全性,它不会为空。

另一种方法可能是有两列,一列作为对 Town 的引用(允许为空),另一列作为自由文本。如果城镇在表中,则使用引用,如果不是,则使用字符串。当然,这会使您的程序逻辑相当复杂。

于 2012-09-04T09:23:59.733 回答