Hibernate中未正确加载集合

时间:2014-09-11 03:11:06

标签: java hibernate

我已将带有Eclipse Link的Java实体加载到我的项目中。这是User - Rol模型的简单关系,但我不知道为什么它不会为用户加载Rol列表。

这是我生成的代码。它正在杀死我,因为日志显示正确的查询,甚至显示它加载rol,但从未出现在用户类。

@Entity
@Table(name = "usuario")
@NamedQuery(name = "Usuario.findAll", query = "SELECT u FROM Usuario u")
public class Usuario implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    private String username;

    //bi-directional many-to-many association to Rol
    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(
            name = "usuario_has_rol",
            joinColumns = {@JoinColumn(name = "usuario_username")},
            inverseJoinColumns = {@JoinColumn(name = "rol_id_rol")})
    private List<Rol> rols;
    // getters and setters
}

Rol类:

@Entity
@Table(name = "rol")
@NamedQuery(name = "Rol.findAll", query = "SELECT r FROM Rol r")
public class Rol implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id_rol")
    private int idRol;

    @Column(name = "rol_name")
    private String rolName;

    //bi-directional many-to-one association to RolHasMenu
    @OneToMany(mappedBy = "rol")
    private List<RolHasMenu> rolHasMenus;

    //bi-directional many-to-many association to Usuario
    @ManyToMany(mappedBy = "rols")
    private List<Usuario> usuarios;
    // getters and setters
}

日志显示以下内容(我可以看到rol正确加载)

21:59:17,112 TRACE EntityReferenceInitializerImpl:245 - hydrating entity state
21:59:17,112 TRACE EntityReferenceInitializerImpl:297 - Initializing object from ResultSet: [org.inkasoft.edustat.model.Rol#2]
21:59:17,113 TRACE AbstractEntityPersister:2901 - Hydrating entity: [org.inkasoft.edustat.model.Rol#2]
21:59:17,113 TRACE BasicExtractor:78 - extracted value ([rol_name2_19_4_] : [VARCHAR]) - [ROL_USER]
21:59:17,113 TRACE BasicExtractor:78 - extracted value ([usuario_1_24_3_] : [VARCHAR]) - [jaxkodex]
21:59:17,113 DEBUG CollectionReferenceInitializerImpl:77 - Found row of collection: [org.inkasoft.edustat.model.Usuario.rols#jaxkodex]
21:59:17,113 TRACE LoadContexts:171 - Constructing collection load context for result set [com.mysql.jdbc.JDBC4ResultSet@3954b0d3]
21:59:17,114 TRACE CollectionLoadContext:112 - Starting attempt to find loading collection [[org.inkasoft.edustat.model.Usuario.rols#jaxkodex]]
21:59:17,114 TRACE CollectionLoadContext:138 - Instantiating new collection [key=jaxkodex, rs=com.mysql.jdbc.JDBC4ResultSet@3954b0d3]
21:59:17,114 TRACE BasicExtractor:78 - extracted value ([rol_id_r2_25_3_] : [INTEGER]) - [2]

1 个答案:

答案 0 :(得分:2)

正如@Chaitanya指出的那样,您需要指定基础列表实现类的类型,

private List<Rol> rols = new ArrayList<Rol>();

或者,在getter方法中

public List<Rol> getRols() {
    if(rols == null) {
        rols = new ArrayList<Rol>();
    }
    return rols;
}