开发者

Why can I not get any results from this rather trivial query?

开发者 https://www.devze.com 2023-04-13 00:35 出处:网络
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

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;
开发者_Python百科    }

    @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]


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


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?

0

精彩评论

暂无评论...
验证码 换一张
取 消