【问题标题】:how to get one side object value when query many side?查询多方时如何获取一侧对象值?
【发布时间】:2012-07-24 06:18:25
【问题描述】:

我使用play框架做web sample excise,遇到了manyToOne相关的问题。
我的对象关系如下:

@Entity 
@Table(name="account")  
public class User extends Model{  

    @Id  
    @Constraints.Required  
    @Formats.NonEmpty  
    @MinLength(4)  
    public String name;  

    @Constraints.Required  
    @Email  
    public String email;  
    public User(String username, String email) {
        this.name       = username;
        this.email      = email;
    }
}
@Entity 
@Table(name="note")  
public class Note  extends Model{  
    @Id  
    public Long id;  

    @Constraints.Required  
    public String title;  

    @Required  
    @ManyToOne  
    public User user;  

    public static Model.Finder<Long,Note> find = new Model.Finder<Long, Note>(Long.class, Note.class);  
    public Note(User author,String title,) {
        this.user           = author;
        this.title          = title;
    /**  
    * Retrieve the user's note  
    */  
    public static List<Note> findByUser(User user) {  
        return find.where().eq("user", user).findList();  
    }  
    ××this test is at another junit test case ××
    @Test  
    public void createNotes()  {  
        User bob = new User("bob","bob@gmail.com");  
        bob.save();  
        Note  note1= new Note(bob, "My notes");  
        note1.save();  
        List<Note> bobNotes = Note.findByUser(bob);  
        Assert.assertEquals(1, bobNotes .size());  
        Note firstNote = bobNotes .get(0);  
        assertNotNull(firstNote);  
        assertEquals(bob, firstNote.user);  
        assertEquals("My notes", firstNote.title);  
        assertEquals("bob", firstNote.user.name);  
        assertEquals("bob@gmail.com", firstNote.user.email);  
    }  

我的问题是:assertEquals("bob", firstNote.user.name) 已通过,但 assertEquals("bob@gmail.com", firstNote.user.email); 失败并显示 firstNote.user.email 为空。

如何获取用户的其他字段?

【问题讨论】:

  • 问题是assertEquals("bob", firstNote.user.name) 通过了,但是assertEquals("bob@gmail.com", firstNote.user.email);失败并显示 firstNote.user.email 为空。那我怎么能得到用户的其他字段,我已经黑了google和stackoverflow都找不到答案,谢谢。
  • 在 POJO 中进行单元测试很奇怪...此外,您的类中缺少 @Entity 注释。
  • 您确定您的 User 构造函数中没有错误。你能把它的代码放上去吗
  • 感谢回复,我已经修改了描述。@nico_ekito,我错过了一些声明。 @ Seb Cesbron,我已经改变了构造函数,谢谢。
  • 请将源码发给构造函数new User("bob","bob@gmail.com");

标签: playframework many-to-one ebean


【解决方案1】:

findByUser方法如下,问题就消失了:

/**  
 * Retrieve the user's note  
 */  
public static List<Note> findByUser(User user) {  
    return find.join("user").where().eq("user", user).findList();  
}  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-28
    • 1970-01-01
    • 2023-02-17
    • 2021-03-14
    • 1970-01-01
    相关资源
    最近更新 更多