【问题标题】:Querying one-to-many model in Google appengine在 Google appengine 中查询一对多模型
【发布时间】:2013-11-15 15:00:58
【问题描述】:

假设我有一个一对多模型,其中涉及存储几本书及其章节,例如

@Entity
public class Book {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Key id;

    private String title;

    @OneToMany(mappedBy = "book", cascade = CascadeType.ALL)
    private List<Chapter> chapters = new ArrayList<Chapter>();

    // getters and setters
}


@Entity
public class Chapter {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Key id;

    private String title;
    private int numPages;

    @ManyToOne(fetch = FetchType.LAZY)
    private Book book;

    // getters and setters
}

然后像这样持久化它

Book b = new Book();
b.setTitle("JDO 4eva");
Chapter c1 = new Chapter();
c1.setTitle("Intro");
c1.setNumPages(10);
b.getChapters().add(c1);
Chapter c2 = new Chapter();
c2.setTitle("Configuration");
c2.setNumPages(9);
b.getChapters().add(c2);

pm.currentTransaction().begin();
try {
    pm.makePersistent(b);
    pm.currentTransaction().commit();
} finally {
    if (pm.currentTransaction().isActive()) {
        pm.currentTransaction().rollback();
    }
}

然而,我的问题是我如何仅选择特定书籍的章节,因为所有章节都存储在同一实体类型中,但没有相应书籍的参考(“外键”)。

例如,在普通的 sql 中,我会像“select * from chapters where book="book_id”一样查询它。appengine 中这个查询的等价物是什么?非常感谢。

注意:出于说明目的,我从here 获得了一些代码。

【问题讨论】:

    标签: sql google-app-engine


    【解决方案1】:

    其实是我自己想出来的。

    假设我要查询的章节书的 Key 字符串是“agl2ZXJzZWZlZWRyDAsSBVRoZW1lGOQUDA”,我使用持久性管理器的 getObjectById() 方法来获取该书对象,然后使用 getter 方法来检索其下的章节列表喜欢;

    Key BookKey = KeyFactory.stringToKey("agl2ZXJzZWZlZWRyDAsSBVRoZW1lGOQUDA");
    Book book = pm.getObjectById(Book.class,BookKey);           
    
    List<Chapter> chapters = book.getChapters();
    
    for (Chapter chapter : chapters) {
    
      //work on your chapters
    }
    

    希望这对某人有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-29
      • 2011-11-10
      • 1970-01-01
      • 2013-05-17
      • 2011-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多