2014-10-21 77 views
0

选择我想从多个表中选择并转换结果使用以JSON ActiveJDBCActiveJDBC从多个表

http://javalite.io/record_selection

我可以做以下,但它当然会在模型书只返回列,我没有看到作者模型中的列。怎样才能做到这一点?

LazyList<Book> book = Book.findBySQL("select books.*, authors.* from books, authors where books.author_id = author.id"); 
jsonOutput = book.toJson(true); 

回答

1

首先,您显然有一对多的关联,因此您不需要使用findBySQL()。这种方法用于框架无法帮助的情况,但您的情况是标准的。 根据这一页:http://javalite.io/one_to_many_associations还有这样一句:http://javalite.io/generation_of_json 你需要写这样的事:

LazyList<Author> authors = Author.findAll().include(Book.class); 
String json = authors.toJson(true); 

或者你可以在同一个写在一行:

String json = Author.findAll().include(Book.class).toJson(true); 

当然,这会将所有作者和他们的书籍加载到内存中。您可能想用适当的标准替换和Author.where(..)

我希望这有助于!

+0

是的,但如果我有一个复杂的查询,从多个表中拉出书籍作者,出版商等......如果没有办法得到这个权利? – nevermind 2014-10-22 16:43:51

+0

我只是想从多个表中做一个通用选择* – nevermind 2014-10-22 16:55:59

+0

在这种情况下,你不能使用模型,因为它们是一个ORM - Object to Relation Mapping :)。我建议看看 [Base#findAll()](http://javalite.github.io/activejdbc/org/javalite/activejdbc/Base.html#findAll-java.lang.String-java.lang.Object ...-) 或[Base#find()](http://javalite.github.io/activejdbc/org/javalite/activejdbc/Base.html#find-java.lang.String-java.lang.Object ...-) 请注意findAll()或all()会将整个结果集加载到你的列表中,而find()会允许你在时间作为游标。 – ipolevoy 2014-10-22 18:52:30