简体   繁体   English

我不知道如何使用 JPQL [AND] 和 [OR]

[英]I don't know how to use JPQL [AND] and [OR]

I made application what it will be able to search book of name and author.I use JPQL to realize it.When I fill two textbox(name of book and author),it search right.But I fill one textbox,it search not found.我做了一个应用程序,它将能够搜索名称和作者的书。我使用 JPQL 来实现它。当我填写两个文本框(书名和作者的名字)时,它搜索正确。但是我填写一个文本框,找不到搜索. How to fix?怎么修?

Book.java书.java

@Table(name = "books")
@NamedQueries({
        @NamedQuery(name = "searchNameAndAuthor", query = "SELECT b FROM Book AS b WHERE b.book_name =:book_name and b.author=:author"),
        @NamedQuery(name = "searchNameAndAuthorCount", query = "SELECT count(b) FROM Book AS b WHERE b.book_name =:book_name and b.author=:author")
})
@Entity
public class Book {
    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column(name = "isbn_code", length = 17)
    private Integer isbn_code;

    @Column(name = "book_name", length = 30, nullable = false)
    private String book_name;

    @Column(name = "author", length = 20)
    private String author;

    @Column(name = "publisher", length = 20)
    private String publisher;

    @Column(name = "publish_date", length = 8)
    private Date publish_date;

    @Column(name = "stock", length = 4)
    private Integer stock;

search.jsp搜索.jsp

<c:import url="/WEB-INF/views/layout/app.jsp">
    <c:param name="content">
        <c:if test="${flush != null}">
            <div id="flush_success">
                <c:out value="${flush}"></c:out>
            </div>
        </c:if>
        <h2>図書館ようこそ</h2>
        <form method="POST" action="<c:url value='/books/search/result' />">
            <label for="book_name">調べたいタイトル</label><br /> <input type="text"
                name="book_name" value="${book_name}" /> <br />
            <br />
            <label for="author">著者</label><br /> <input type="text"
                name="author" value="${author}" /> <br />
            <br />
            <button type="submit">検索</button>
        </form>
    </c:param>
</c:import>

You need to handle the null case also.您还需要处理 null 案例。 A way can be checking is the parameter is null as OR condition一种可以检查的方法是参数是 null 作为 OR 条件

SELECT b FROM Book AS b WHERE (:book_name IS NULL OR b.book_name =:book_name) 
                          and (:author IS NULL OR  b.author=:author)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM