我已将带有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]

最佳答案

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

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


另外,在吸气方法

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

07-24 14:43