JPA:子对象的自动加载不能按预期工作

时间:2012-08-21 21:35:17

标签: jpa persistence jpa-2.0 eclipselink

我有以下两个实体:

class Role {
  @Id Long id;
  @Column String email;
  String role;
  @ManyToOne User user;
}

class User {
  @Id Long id;
  @Column(unique=true) String email;
  String password;

  @OneToMany(mappedBy = "user")
  @OrderBy("role asc")
  List<Role> roles;
}

SQL是:

CREATE TABLE USER (
ID BIGINT NOT NULL, 
EMAIL VARCHAR(255) UNIQUE, 
PASSWORD VARCHAR(255), 
PRIMARY KEY (ID)
)
CREATE TABLE ROLE (
ID BIGINT NOT NULL, 
EMAIL VARCHAR(255),
ROLE VARCHAR(255), 
USER_ID BIGINT, 
PRIMARY KEY (ID),
FOREIGN KEY (USER_ID) REFERENCES USER(ID)
)

以下JUnit在最后一行失败。我从子进程中自动加载了用户(父进程),但是我没有从父进程中自动加载子进程。我做错了什么?

    Role r = em.createQuery("select r from Role r where r.email = :email", Role.class)
            .setParameter("email", "john@google.com")
            .getSingleResult();
    assertEquals("registered", r.role());
    assertEquals("john@google.com", r.user().email());

    User u = em.createQuery("select u from User u where u.email = :email", User.class)
            .setParameter("email", "john@google.com")
            .getSingleResult();

    assertEquals("john@google.com", u.email());
    assertEquals("asdf", u.password());

    assertEquals(1, u.roles().size()); FAILS HERE!!!
    assertEquals("registered", u.roles().get(0).role());

我正在使用EclipseLink 2.3.2(JPA)

1 个答案:

答案 0 :(得分:1)

有多种方法可以告诉你应该如何加载另一个和一个关系。一个是在查询级别,使用fetch join,如下所示:

select u from User u left join FETCH u.roles r where...

另一个是关系声明级别,如下所示:

class User {
  @Id Long id;
  @Column(unique=true) String email;
  String password;

  @OneToMany(mappedBy = "user", fetch=FetchType.EAGER)
  @OrderBy("role asc")
  List<Role> roles;
}

当你加载一个角色时,你也得到没有任何特殊注释或加入你的查询的用户的原因是JPA中的ManyToOne关系默认为fetch = EAGER:

http://docs.oracle.com/javaee/5/api/javax/persistence/ManyToOne.html#fetch()

虽然默认情况下一对多有fetch = lazy:

http://docs.oracle.com/javaee/5/api/javax/persistence/OneToMany.html#fetch()