问题
I have a portlet, which can add/update/delete books and add authors. Moreover, you can choose existing authors when you try to add book.
And now I need to show how many books were written by each author in "author" table. How can I do it? Im a newbie in liferay and I even have no idea.
It's my service.xml
<entity name="Book" local-service="true" remote-service="true" cache-enabled="false">
<column name="bookId" type="long" primary="true" />
<column name="bookName" type="String" />
<column name="bookDescription" type="String" />
<column name="authors" type="Collection" entity="Author" mapping-table="Books_Authors" />
<finder return-type="Collection" name="bookName">
<finder-column name="bookName"></finder-column>
</finder>
</entity>
<entity name="Author" local-service="true" remote-service="true" cache-enabled="false">
<column name="authorId" type="long" primary="true" />
<column name="authorName" type="String" />
<column name="books" type="Collection" entity="Book" mapping-table="Books_Authors" />
</entity>
回答1:
Service Builder is your friend.
You just need to add a finder in your book entity in service.xml
. If your entity has a field named author
:
<finder name="Author" return-type="Collection">
<finder-column name="author" />
</finder>
The execution of build-service will generate the methods BookUtil.findByAuthor()
and BookUtil.countByAuthor()
.
You can implement now the corresponding methods in BookLocalServiceImpl
, calling the previous, and after another run of build-serivce, they're available in your Util
class. Something like
public List<Book> getByAuthor(String author) {
return getPersistence().findByAuthor(author);
}
public int countByAuthor(String author) {
return getPersistence().countByAuthor(author);
}
After the last call to build-service you can call them from your BookLocalServiceUtil
.
If you just want the count, don't retrieve all the collection. If there are many records, it's a bad idea. Invoke the count instead.
来源:https://stackoverflow.com/questions/39332811/liferay-and-relationships-in-it