Question

I am using Spring Roo with repository layers. I have two classes: Document (with the title of the document) and FilledDocument (that contains the related Document). Like this:

public class Document {

    /**
     */
    @NotNull
    private String titleDocument;
    ...
}

public class FilledDocument {

    /**
     */
    @OneToOne
    private Document relatedDocument;
    ...
}

I would want to create a finder for the class FilledDocument that match for title inside of the atribute relatedDocument.

I am using a solution that isnt elegant and efficient. In my controller I have:

@RequestMapping(params = "find", produces = "text/html")
public String findFilledDocumentsByTitleDocumentContaining(@RequestParam(value = "title", required = true) String title, Model uiModel) {

    LinkedList<FilledDocument> allFilledDocuments = new LinkedList<FilledDocument>();
    allFilledDocuments.addAll(filledDocumentService.findAllFilledDocuments());

    ArrayList<FilledDocument> filledDocuments=new ArrayList<FilledDocument>();

    for( FilledDocument filledDocument : allFilledDocuments ) {
        if( filledDocument.getRelatedDocument().getTitleDocument().toLowerCase().contains(title.toLowerCase()) == true ) {
            filledDocuments.add(filledDocument);
        }
    }       

    uiModel.addAttribute("filleddocuments", filledDocuments);
    return "filleddocuments/list";
}

I am reading this Spring Data JPA - Reference Documentation and I am trying with @Query in the repository class, like this:

@Query("select f from FilledDocument f where f.relatedDocument.titleDocument containing = ?1")
public ArrayList<FilledDocument> findFilledDocumentByTitleDocument(@Param("titleDocument") String titleDocument);

but it doesnt work. Any ideas?

Was it helpful?

Solution

If you are using Spring Data JPA 1.3.1 or newer that you can just write :

@Query("select f from FilledDocument f where f.relatedDocument.titleDocument like %:title%")
List<FilledDocument> findFilledDocumentByTitleDocument(@Param("title") String titleDocument);

If you are stuck on an older version then your code would be:

@Query("select f from FilledDocument f where f.relatedDocument.titleDocument like :title")
List<FilledDocument> findFilledDocumentByTitleDocument(@Param("title") String titleDocument);

And when you call the findFilledDocumentByTitleDocument method you need to pass

"%"+title+"%"

as an argument.

Check out this blog post for the full story and section 1.3.4 of the documentation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top