为什么我无法从这个相当简单的查询中获得任何结果?

发布于 2024-12-10 00:14:46 字数 5143 浏览 0 评论 0原文

我试图从一个相当简单的查询中获取结果,并将这些结果写在 jsp 页面上。使用 Netbeans 运行 Glassfish 3.1。当我运行该项目时,我得到一个从例程返回的空列表。

当我右键单击“服务”中的表并点击“查看数据”时,我可以看到该表已填充,当我将查询复制并粘贴到 SQL 命令窗口并运行它时,它给出了长度为 2 的预期列表

。几个类似的问题(例如这个),其中没有一个似乎是有很大帮助。我对此很陌生,所以我可能不明白其他问题之一的解决方案。

这里有很多因素在起作用,我不太确定要包括哪些因素。我已经包含了执行查询的例程、调用该例程的 JSP 代码、我正在使用的实体类以及项目运行时获得的服务器日志的输出。如果需要更多信息,请告诉我,我会提供。

我真的很感谢任何帮助。

Griff

执行查询的例程:

public static LinkedList<String> getCategories(EntityManager entityManager) {
    try {
        Query query = entityManager.createQuery(
                "SELECT DISTINCT i.category from ItemEntity i");
        List resultList = query.getResultList();
        if (!resultList.isEmpty()) {
            return new LinkedList<String>(resultList);
        }
    } catch(Exception e) {
        System.out.println(e);
    } finally {
        return new LinkedList<String>();
    }
}

调用例程的 JSP 代码:

<body>
    <h1>Store</h1>
    <h2>Categories</h2>
    <%
        Context environmentContext 
                = (Context) new InitialContext().lookup("java:comp/env");
        EntityManager entityManager 
                = (EntityManager) environmentContext.lookup("persistence/dbunit");

        LinkedList<String> categories = DataBase.getCategories(entityManager);

        ListIterator<String> categoryIterator = categories.listIterator();
        String category = "";
    %>

    <form action="category.jsp">
        <%  while (categoryIterator.hasNext()) { %>
                <%  category = categoryIterator.next(); %>
                <input type="submit" class="submitButtonAsLink" value="<%= category %>" name="<%= category %>" /><br />
        <% } %>
    </form> 
</body>

ItemEntity.java:

@Entity
public class ItemEntity implements Serializable {
    private static final long serialVersionUID = 1L;

@Id @GeneratedValue(strategy = GenerationType.AUTO)
    private String id;

    private String title;
    private String longDescription;
    private double cost;
    private String category;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set  
        if (!(object instanceof ItemEntity)) {
            return false;
        }
        ItemEntity other = (ItemEntity) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "store.model.entities.ItemTable[ id=" + id + " ]";
    }

    //getters and setters omitted. 
    //There are getters and setters for every field except id.
}

服务器日志:

INFO: file:/Users/griffgeorge/Dropbox/school/design-arch/labs/Lab4Exercise/build/web/WEB-INF/classes/_Lab4ExercisePU logout successful
INFO: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
INFO: EclipseLink, version: Eclipse Persistence Services - 2.3.0.v20110604-r9504
INFO: file:/Users/griffgeorge/Dropbox/school/design-arch/labs/Lab4Exercise/build/web/WEB-INF/classes/_Lab4ExercisePU login successful
WARNING: Multiple [2] JMX MBeanServer instances exist, we will use the server at index [0] : [com.sun.enterprise.v3.admin.DynamicInterceptor@1ed957d].
WARNING: JMX MBeanServer in use: [com.sun.enterprise.v3.admin.DynamicInterceptor@1ed957d] from index [0] 
WARNING: JMX MBeanServer in use: [com.sun.jmx.mbeanserver.JmxMBeanServer@1a84f3c] from index [1] 
WARNING: PER01000: Got SQLException executing statement "CREATE TABLE ITEMENTITY (ID VARCHAR(255) NOT NULL, CATEGORY VARCHAR(255), COST FLOAT, LONGDESCRIPTION VARCHAR(255), TITLE VARCHAR(255), PRIMARY KEY (ID))": java.sql.SQLException: Table/View 'ITEMENTITY' already exists in Schema 'APP'.
WARNING: PER01000: Got SQLException executing statement "CREATE TABLE SEQUENCE (SEQ_NAME VARCHAR(50) NOT NULL, SEQ_COUNT DECIMAL(15), PRIMARY KEY (SEQ_NAME))": java.sql.SQLException: Table/View 'SEQUENCE' already exists in Schema 'APP'.
WARNING: PER01000: Got SQLException executing statement "INSERT INTO SEQUENCE(SEQ_NAME, SEQ_COUNT) values ('SEQ_GEN', 0)": java.sql.SQLIntegrityConstraintViolationException: The statement was aborted because it would have caused a duplicate key value in a unique or primary key constraint or unique index identified by 'SQL111012114449870' defined on 'SEQUENCE'.
INFO: WEB0671: Loading application [Lab4Exercise] at [/Lab4Exercise]

I'm trying to get results from a rather trivial query, and write out those results on a jsp page. Running Glassfish 3.1, using Netbeans. When I run the project, I get an empty list returned from the routine.

When I right click the table in Services and hit View Data, I can see the table is populated, and when I copy and past the query into the SQL Command window and run it, it gives the expected list of length 2.

There are a few similar questions (like this one), none of which seemed to be of much help. I am new at this, so I may not have understood a solution to one of the other questions.

There are a lot of factors at play here, and I'm not really sure what to include. I have included the routine doing the query, the JSP Code calling that routine, the entity class I'm using, and the output of the server log that I get when the project is run. If more information is needed, let me know and I'll put it up.

I really appreciate any help.

Griff

Routine doing the query:

public static LinkedList<String> getCategories(EntityManager entityManager) {
    try {
        Query query = entityManager.createQuery(
                "SELECT DISTINCT i.category from ItemEntity i");
        List resultList = query.getResultList();
        if (!resultList.isEmpty()) {
            return new LinkedList<String>(resultList);
        }
    } catch(Exception e) {
        System.out.println(e);
    } finally {
        return new LinkedList<String>();
    }
}

The JSP Code calling the routine:

<body>
    <h1>Store</h1>
    <h2>Categories</h2>
    <%
        Context environmentContext 
                = (Context) new InitialContext().lookup("java:comp/env");
        EntityManager entityManager 
                = (EntityManager) environmentContext.lookup("persistence/dbunit");

        LinkedList<String> categories = DataBase.getCategories(entityManager);

        ListIterator<String> categoryIterator = categories.listIterator();
        String category = "";
    %>

    <form action="category.jsp">
        <%  while (categoryIterator.hasNext()) { %>
                <%  category = categoryIterator.next(); %>
                <input type="submit" class="submitButtonAsLink" value="<%= category %>" name="<%= category %>" /><br />
        <% } %>
    </form> 
</body>

ItemEntity.java:

@Entity
public class ItemEntity implements Serializable {
    private static final long serialVersionUID = 1L;

@Id @GeneratedValue(strategy = GenerationType.AUTO)
    private String id;

    private String title;
    private String longDescription;
    private double cost;
    private String category;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set  
        if (!(object instanceof ItemEntity)) {
            return false;
        }
        ItemEntity other = (ItemEntity) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "store.model.entities.ItemTable[ id=" + id + " ]";
    }

    //getters and setters omitted. 
    //There are getters and setters for every field except id.
}

Server Log:

INFO: file:/Users/griffgeorge/Dropbox/school/design-arch/labs/Lab4Exercise/build/web/WEB-INF/classes/_Lab4ExercisePU logout successful
INFO: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
INFO: EclipseLink, version: Eclipse Persistence Services - 2.3.0.v20110604-r9504
INFO: file:/Users/griffgeorge/Dropbox/school/design-arch/labs/Lab4Exercise/build/web/WEB-INF/classes/_Lab4ExercisePU login successful
WARNING: Multiple [2] JMX MBeanServer instances exist, we will use the server at index [0] : [com.sun.enterprise.v3.admin.DynamicInterceptor@1ed957d].
WARNING: JMX MBeanServer in use: [com.sun.enterprise.v3.admin.DynamicInterceptor@1ed957d] from index [0] 
WARNING: JMX MBeanServer in use: [com.sun.jmx.mbeanserver.JmxMBeanServer@1a84f3c] from index [1] 
WARNING: PER01000: Got SQLException executing statement "CREATE TABLE ITEMENTITY (ID VARCHAR(255) NOT NULL, CATEGORY VARCHAR(255), COST FLOAT, LONGDESCRIPTION VARCHAR(255), TITLE VARCHAR(255), PRIMARY KEY (ID))": java.sql.SQLException: Table/View 'ITEMENTITY' already exists in Schema 'APP'.
WARNING: PER01000: Got SQLException executing statement "CREATE TABLE SEQUENCE (SEQ_NAME VARCHAR(50) NOT NULL, SEQ_COUNT DECIMAL(15), PRIMARY KEY (SEQ_NAME))": java.sql.SQLException: Table/View 'SEQUENCE' already exists in Schema 'APP'.
WARNING: PER01000: Got SQLException executing statement "INSERT INTO SEQUENCE(SEQ_NAME, SEQ_COUNT) values ('SEQ_GEN', 0)": java.sql.SQLIntegrityConstraintViolationException: The statement was aborted because it would have caused a duplicate key value in a unique or primary key constraint or unique index identified by 'SQL111012114449870' defined on 'SEQUENCE'.
INFO: WEB0671: Loading application [Lab4Exercise] at [/Lab4Exercise]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梨涡 2024-12-17 00:14:46

您的 getCategories() 方法始终返回一个空列表,因为 finally 中的 return 始终运行(即使在第一个 return 之后)代码>)。

您根本不需要 finally 子句。您可以简化为

public static LinkedList<String> getCategories(EntityManager entityManager) {
    try {
        Query query = entityManager.createQuery(
                "SELECT DISTINCT i.category from ItemEntity i");
        return new LinkedList<String>(query.getResultList());
    } catch(Exception e) {
        System.out.println(e);
        return new LinkedList<String>();
    }
}

如果您的 query.getResultList() 不为空,则它返回一个非空的字符串链接列表。

如果您的 query.getResultList() 为空,那么它将返回一个空的字符串链接列表。

如果发生异常,则返回一个空列表。
正如您之前所看到的,即使您的查询正在返回数据,它也总是返回一个空列表。

为了证明finally中的返回是通过的,看一下这个

public class TestFinally {
    public static void main(String[] args) {
        System.out.println(TestFinally.test());
    }

    public static int test() {
        try {
            return 1;
        } finally {
            return 0;
        }  
    }
}

返回

0

Your getCategories() method always returns an empty list, because the return in finally always runs (even after the first return).

You don't need a finally clause there at all. You can simplify to this

public static LinkedList<String> getCategories(EntityManager entityManager) {
    try {
        Query query = entityManager.createQuery(
                "SELECT DISTINCT i.category from ItemEntity i");
        return new LinkedList<String>(query.getResultList());
    } catch(Exception e) {
        System.out.println(e);
        return new LinkedList<String>();
    }
}

If your query.getResultList() is not empty, then it returns a non empty linked list of strings.

If your query.getResultList() is empty, then it returns an empty linked list of strings.

If an exception happens then it returns an empty list.
As you had before, it was always returning an empty list, even if your query was returning data.

To prove that the return in finally is the one that gets through, take a look at this

public class TestFinally {
    public static void main(String[] args) {
        System.out.println(TestFinally.test());
    }

    public static int test() {
        try {
            return 1;
        } finally {
            return 0;
        }  
    }
}

returns

0
初见你 2024-12-17 00:14:46

你的 persistence.xml 怎么样?它指向您期望的数据源吗?那么该数据源是否指向您期望的连接池?

how about your persistence.xml? is that pointing to the datasource you expect? and then is that datasource pointing to the connection pool you expect?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文