0

DAO-object gets from DB only limited count of objects. Only Clear - Build - Deploy can help.

I have DB with connected by foreign keys entities. One of them is User. Other one - Book. Those entities are stored in tables Users and Library. In table Users stores 100 rows. In table Library stores 1050 rows.

User entity class.

public class User {

private long id;
private String firstName;
private String lastName;
private String email;
private String login;
private String password;
private Gender gender;
private boolean confirmed;
private boolean banned;
private String registrationDate;
private boolean notify;
private Role role;

@Override
public String toString(){
    return id + " " + firstName + " " + lastName + " " + email + " " + login + " " + password + " " + gender
            + " " + confirmed + " " + banned + " " + registrationDate + " " + notify + " " + role;
}

public List<String> toStringList(){
    List<String> result = new ArrayList<String>();
    result.add(String.valueOf(id));
    result.add(firstName);
    result.add(lastName);
    result.add(email);
    result.add(login);
    result.add(password);
    result.add(String.valueOf(gender.toInt()));
    result.add(confirmed?"1":"0");
    result.add(banned?"1":"0");
    result.add(registrationDate);
    result.add(notify?"1":"0");
    result.add(String.valueOf(role.getId()));

    return result;
}

public User() {
}

public User(long id) {
    this.id = id;
}

public boolean isBanned() {
    return banned;
}

public void setBanned(boolean banned) {
    this.banned = banned;
}

public boolean isConfirmed() {
    return confirmed;
}

public void setConfirmed(boolean confirmed) {
    this.confirmed = confirmed;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public String getFirstName() {
    return firstName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

public Gender getGender() {
    return gender;
}

public void setGender(Gender gender) {
    this.gender = gender;
}

public long getId() {
    return id;
}

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

public String getLastName() {
    return lastName;
}

public void setLastName(String lastName) {
    this.lastName = lastName;
}

public String getLogin() {
    return login;
}

public void setLogin(String login) {
    this.login = login;
}

public boolean isNotify() {
    return notify;
}

public void setNotify(boolean notify) {
    this.notify = notify;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

public String getRegistrationDate() {
    return registrationDate;
}

public void setRegistrationDate(String registrationDate) {
    this.registrationDate = registrationDate.substring(0, 10);
}

public Role getRole() {
    return role;
}

public void setRole(Role role) {
    this.role = role;
}

}

UserDao class with CRUD methods.

    public class UserDao {

private Connection connection;

public UserDao() {
    connection = ConnectionProvider.getConnection();
}

public boolean createUser(User user) {
    try {
            String sqlRequest =
                    "INSERT INTO Users (ID,FIRST_NAME,LAST_NAME,EMAIL,LOGIN,PASSWORD," +
                    "GENDER,CONFIRMED,BANNED,REGISTRATION_DATE,NOTIFY,ROLE) " +
                    "values(?,'?','?','?','?','?',?, ?, ?, TO_DATE('?','yyyy-mm-dd'), ?, ?)";
        PreparedStatement ps = connection.prepareStatement(sqlRequest);

        ps.setLong(1, user.getId());
        ps.setString(2, user.getFirstName());
        ps.setString(3, user.getLastName());
        ps.setString(4, user.getEmail());
        ps.setString(5, user.getLogin());
        ps.setString(6, user.getPassword());
        ps.setInt(7, user.getGender().toInt());
        ps.setBoolean(8, user.isConfirmed());
        ps.setBoolean(9, user.isBanned());
        ps.setString(10, user.getRegistrationDate());
        ps.setBoolean(11, user.isNotify());
        ps.setInt(12, user.getRole().getId());
        ps.executeUpdate();

        connection.commit();

    } catch (SQLException e) {
        e.printStackTrace();
        return false;
    }
    return true;
}

public User getUserById(long id) {
    User user = new User();
    try {
            String sqlRequest =
                    "SELECT * FROM Users WHERE id=?";
        PreparedStatement ps = connection.prepareStatement(sqlRequest);

        ps.setLong(1, id);
        ResultSet rs = ps.executeQuery();

        if (rs.next()) {
            user.setId(rs.getLong("id"));
            user.setFirstName(rs.getString("FIRST_NAME"));
            user.setLastName(rs.getString("LAST_NAME"));
            user.setEmail(rs.getString("EMAIL"));
            user.setLogin(rs.getString("LOGIN"));
            user.setPassword(rs.getString("PASSWORD"));
            user.setGender(Gender.getGender(rs.getInt("GENDER")));
            user.setConfirmed(rs.getInt("CONFIRMED")==1);
            user.setBanned(rs.getInt("BANNED")==1);
            //String[] regDate = rs.getString("REGISTRATION_DATE").split(".");
            //user.setRegistrationDate(Date.valueOf(regDate[2]+"-"+regDate[1]+"-"+regDate[0]));
            user.setRegistrationDate(rs.getString("REGISTRATION_DATE"));
            user.setNotify(rs.getInt("NOTIFY")==1);
            user.setRole(new RoleDao().getRoleById(rs.getInt("ROLE")));
            //user.setRole(new Role(1, "Administrator"));
        }

    } catch (SQLException e) {
        e.printStackTrace();
    }
    return user;
}

public List<User> getAllUsers() {
    List<User> users = new ArrayList<User>();
    try {
            String sqlRequest =
                    "SELECT * FROM Users";
        PreparedStatement ps = connection.prepareStatement(sqlRequest);

        ResultSet rs = ps.executeQuery();

        while (rs.next()) {
            User user = new User();
            user.setId(rs.getLong("id"));
            user.setFirstName(rs.getString("FIRST_NAME"));
            user.setLastName(rs.getString("LAST_NAME"));
            user.setEmail(rs.getString("EMAIL"));
            user.setLogin(rs.getString("LOGIN"));
            user.setPassword(rs.getString("PASSWORD"));
            user.setGender(Gender.getGender(rs.getInt("GENDER")));
            user.setConfirmed(rs.getInt("CONFIRMED")==1);
            user.setBanned(rs.getInt("BANNED")==1);
            user.setRegistrationDate(rs.getString("REGISTRATION_DATE"));
            user.setNotify(rs.getInt("NOTIFY")==1);
            user.setRole(new RoleDao().getRoleById(rs.getInt("ROLE")));
            users.add(user);
        }

    } catch (SQLException e) {
        e.printStackTrace();
    }
    return users;
}

public boolean removeUser(int id) {
    try {
            String sqlRequest = "DELETE FROM users WHERE id=?";
        PreparedStatement ps = connection.prepareStatement(sqlRequest);
        ps.setInt(1, id);
        ps.executeUpdate();
        connection.commit();

    } catch (SQLException e) {
        e.printStackTrace();
        return false;
    }
    return true;
  }

public boolean  editUser(User user) {
    try {
            String sqlRequest = "UPDATE Users SET FIRST_NAME='?', LAST_NAME='?', " +
                    "EMAIL='?', LOGIN='?', PASSWORD='?', GENDER=?, CONFIRMED=?, " +
                    "BANNED=?, REGISTRATION_DATE=TO_DATE('?','yyyy-mm-dd'), NOTIFY=?, ROLE=? WHERE ID=?";
        PreparedStatement ps = connection.prepareStatement(sqlRequest);

        String[] userParams = new String[12];
        userParams = user.toStringList().toArray(userParams);
        for(int i=1; i < 12; i++)
            ps.setString(i, userParams[i]);
        ps.setString(12, userParams[0]);

        ps.executeUpdate();
        connection.prepareStatement("commit").executeUpdate();
        connection.commit();

    } catch (SQLException e) {
        e.printStackTrace();
        return false;
    }
    return true;
}

}

Entity class and DAO for Library are similarly.

ConnectionProvider class. Stores Connection like singleton object.

public class ConnectionProvider {

private static Connection con = null;

private ConnectionProvider(){}

public static Connection getConnection() {
    if (con != null)
        return con;
    else {
        try {
            Locale.setDefault(Locale.ENGLISH);
            Context ic = new InitialContext();
            DataSource dataSource = (DataSource) ic.lookup("jdbc/test");
            con = dataSource.getConnection();
        }
        catch(NamingException e)
        {
            System.out.println("Cannot retrieve jdbc/test"+e.getMessage());
        }
        catch(SQLException e)
        {
            e.printStackTrace();
        }
        return con;
    }

}

}

Body of JSP page for testing Dao. When this code works, you can refresh page 3 times correctly. And on 4th time you'll get blank page.

    <%
        List<User> users = new UserDao().getAllUsers();
        for(User u : users){
           out.println(u.toString()+"<br/>");
        }
 %>

When this code works, you can load page 1 time correctly (you'll see all 1050 records). And on refreshing you'll get blank page.

        <%
        List<Library> books = new LibraryDao().getAllBooks();
        for(TransferObject.Library b : books){
         out.println(b.toString()+"<br/>");
        }
    %>

Please, if anyone knows, say what is my pronlem. It's very oddly problem and I don't understand why it happens. I can see limited count of records from DB and then methods getAllUsers() or getAllBooks() returns null.

Anton
  • 5
  • 2
  • 2
    I would remove all `catch` statements or replace their block content with some `throw MyException("Friendly message", e);` You are [hiding the errors](http://en.wikipedia.org/wiki/Error_hiding) and must check your log to see the printed stack traces. Also, hiding errors may lead to undefined behavior in your application, so you should really avoid it! – ericbn Jan 02 '14 at 14:30
  • 1
    Also, you should make sure you're [closing all resources](http://stackoverflow.com/questions/4508172/how-to-properly-clean-up-jdbc-resources-in-java). That means closing `PreparedStatement`, `ResultSet` and also `Connection` after each time you are done using them in a method. If you don't close them, you will get out of resources after a while. That is probably you problem. – ericbn Jan 02 '14 at 14:44
  • Write a simple JSP where you retrieve the list of all users / books more then one time and try to show all your results. Also replace `e.printStackTrace()`in `getAllXXX()`-methods with `throw new IllegalStateException("Error occurred!", e);`. And post the result of your test here. – Vlad Jan 02 '14 at 15:33
  • @Vlad Glassfish writes: type Exception report message descriptionThe server encountered an internal error () that prevented it from fulfilling this request. exception java.lang.IllegalStateException: Error occurred! note The full stack traces of the exception and its root causes are available in the Sun GlassFish Enterprise Server v2.1.1 logs. – Anton Jan 02 '14 at 17:56
  • and what says the logfile of glasfish? What's the reason of the exception? – Vlad Jan 02 '14 at 18:49
  • @Vlad I had shorted because there is limited length of message. java.sql.SQLException: ORA-01000: maximum open cursors exceeded TWO MY CLASSES good.DAO.UserDao.getUserById(UserDao.java:73) good.DAO.LibraryDao.getAllBooks(LibraryDao.java:103) AND OTHER at oracle.jdbc.driver org.apache.jsp.testpage_005fgood_jsp._jspService org.apache.jasper.runtime.HttpJspBase.service org.apache.jasper.servlet javax.servlet.http.HttpServlet.service org.apache.catalina com.sun.enterprise.web – Anton Jan 02 '14 at 19:47
  • @Vlad line 103 of LibraryDao.java library.setUser(new UserDao().getUserById(rs.getLong("USERs"))); ||||||| line 73 of UserDao.java ResultSet rs = ps.executeQuery(); – Anton Jan 02 '14 at 19:50

1 Answers1

0

You should close connection each time after retrieving the data. To save resources you can use Connection Pool to share connections. The reason for the error is a not resetted database cursor. Try to close Connection after each operation and create a new one before every new request. The connection pool can be applyed later.

Vlad
  • 471
  • 5
  • 7