JPA:@SqlResultSetMapping给了我两个对象,而不是一个

时间:2011-07-13 18:23:23

标签: java jpa one-to-many sqlresultsetmapping

我正在尝试做一些NativeQueries,但我坚持使用@SqlResultSetMapping配置。

我有这些课程:

@Entity  
public class LocalUser implements Serializable {  
    private static final long serialVersionUID = 1265845L;  
    @Id  
    private String username;  
    @Column(nullable=false)  
    private String password;  

    @OneToMany  
    private List<RoleName> roles;  

    public LocalUser() {  
    }  

    public LocalUser(String username, String password, List<RoleName> roles) {  
        this.username = username;  
        this.password = password;  
        this.roles = roles;  
    }      

    public String getPassword() {  
        return password;  
    }  

    public void setPassword(String password) {  
        this.password = password;  
    }  

    public List<RoleName> getRoles() {  
        return roles;  
    }  

    public void setRoles(List<RoleName> roles) {  
        this.roles = roles;  
    }  

    public String getUsername() {  
        return username;  
    }  

    public void setUsername(String username) {  
        this.username = username;  
    }  
}  

@Entity  
public class RoleName implements Serializable {  
    private static final long serialVersionUID = 12598741564894L;  
    @Id  
    @GeneratedValue(strategy = GenerationType.IDENTITY)  
    private Long id;  

    private String roleName;  

    public RoleName() {  
    }  

    public RoleName(Long id, String roleName) {  
        this.id = id;  
        this.roleName = roleName;  
    }  

    public RoleName(String roleName) {  
        this.roleName = roleName;  
    }  

    public Long getId() {  
        return id;  
    }  

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

    public String getRoleName() {  
        return roleName;  
    }  

    public void setRoleName(String roleName) {  
        this.roleName = roleName;  
    }  
}

我的问题是,如何为类LocalUser编写propper @SqlResultSetMapping。我的测试SQL语句是:

select 'user' as username, 'passwd' as password, 1 as id, 'admin' as roleName;  

我想获得一个Entity Local用户,其中包含用户名user,密码passwd和一个角色列表,其中admin是id为1.

我想到这样的事情:

@SqlResultSetMapping(name="LocalUserMapping",  
    entities={  
        @EntityResult(entityClass=LocalUser.class,fields={  
            @FieldResult(name="username",column="username"),  
            @FieldResult(name="password",column="password")  
        }),  
        @EntityResult(entityClass=RoleName.class,fields={  
            @FieldResult(name="id",column="id"),  
            @FieldResult(name="roleName",column="roleName")  
        })  
    })

但它给了我两个对象,而不是一个。有人能帮帮我吗?感谢。

1 个答案:

答案 0 :(得分:0)

这两个对象是使用entityClass=注释(2x,一个用于LocalUser,一个用于RoleName)产生的。将它们组合成一个entityClass定义,将返回一个对象。