@Loader在注释上是否正常工作(使用JPA)?

时间:2011-06-16 02:16:34

标签: hibernate

这是一个有点人为的例子,旨在表明一点。以下是通过关系和命名查询链接的两个实体类:

@Entity
@NamedNativeQuery(name = "loadFoo",
              query = "select * from foos where bar_id = ?",
              resultClass = Foo.class)                  
public class Bar {
@Id private int id;

@ManyToOne @Loader(namedQuery = "loadFoo") private Foo foo;

public void setId(int id) { this.id = id; }

public int getId() { return id; }

public void setFoo(Foo foo) { this.foo = foo; }

public Foo getFoo() { return foo; }
}

然后:

@Entity @Table(name="foos")
public class Foo {
@Id @GeneratedValue private int id;

@Column(name="bar_id") private int barId;

public void setBarId(int barId) { this.barId = barId; }

public int getBarId() { return barId; }

public void setId(int id) { this.id = id; }

public int getId() { return id; }
}

奇怪的是,命名查询在单元测试中运行得很好:

以下是设置:

    Bar bar = new Bar();
    entityManager.persist(bar);
    entityManager.flush();

    Foo foo = new Foo();
    foo.setBarId(bar.getId());

    entityManager.persist(foo);
    entityManager.flush();
    entityManager.clear();

这正确地返回Foo,因此命名查询似乎没有问题:

    Foo foo2 = (Foo) entityManager.createNamedQuery("loadFoo").setParameter(1, bar.getId()).getSingleResult();

但负载没有:

    Bar bar2 = entityManager.find(Bar.class, bar.getId());
    Foo foo3 = bar2.getFoo();       
    assertEquals(foo2.getId(), foo3.getId());

没有抛出任何错误。返回的对象只是null。 @Loader注释实际上是由持久性单元处理的,因为如果我使命名查询无效,则在调用getFoo()时将抛出异常。但它永远不会返回正确的值。

1 个答案:

答案 0 :(得分:1)

@Loader只能应用于类或集合,而不能应用于@ * ToOne。 在您的情况下,您需要将@Loader注释放在类Foo上。