Questions tagged [javabeans]

A javabean is a custom class which often represents real-world data and encapsulates private properties by public getter and setter methods. For example, User, Product, Order, etc.

Javabeans

A javabean is a custom class which often represents real-world data and encapsulates private properties by public getter and setter methods. For example, User, Product, Order, etc. In applications using a database, they are often 1:1 mapped to a database table. A single database row can then be represented by a single javabean instance.

Basic example

Here's an example of a javabean representing an User (some newlines are omitted for brevity):

public class User implements java.io.Serializable {

    // Properties.
    private Long id;
    private String name;
    private Date birthdate;
    
    // Getters.
    public Long getId() { return id; }
    public String getName() { return name; }
    public Date getBirthdate() { return birthdate; }
    
    // Setters.
    public void setId(Long id) { this.id = id; }
    public void setName(String name) { this.name = name; }
    public void setBirthdate(Date birthdate) { this.birthdate = birthdate; }

    // Important java.lang.Object overrides.
    public boolean equals(Object other) {
        return (other instanceof User) && (id != null) ? id.equals(((User) other).id) : (other == this);
    }
    public int hashCode() {
        return (id != null) ? (getClass().hashCode() + id.hashCode()) : super.hashCode();
    }
    public String toString() {
        return String.format("User[id=%d,name=%s,birthdate=%d]", id, name, birthdate);
    }
}

Implementing Serializable is mandatory, in order to be able to persist or transfer javabeans outside Java's memory; E.G. on a disk drive, a database, or over the network. In case of web applications, some servers will do that with HTTP sessions (e.g. save to disk before restart, or share with other servers in cluster). Any internal variables that do not have getters/setters should be marked transient to prevent them from being serialized.

Implementing toString() is not mandatory, but it is very useful if you'd like to be able to log/print the object to a logger/stdout and see a bit more detail than only com.example.User@1235678.

Implementing equals() and hashCode() is mandatory for the case you'd like to collect them in a Set or a HashMap, otherwise different instances of javabeans which actually contain/represent the same data would be treated as different representations.

Code generation

A bit sane IDE like Eclipse/IntelliJ/Netbeans can autogenerate all necessary constructors and methods based on only a bunch of fields. So you could just start off with only the necessary fields:

public class User implements java.io.Serializable {

    private Long id;
    private String name;
    private Date birthdate;

}

And then right click somewhere in the source code and choose Source and then you'll get a list of various useful Javabean-related options such as generating of getters/setters, hashCode()/equals() and toString().

enter image description here


Usage example - JDBC

In for example a JDBC database access object (DAO) class you can use it to create a list of users wherein you store the data of the User table in the database:

public List<User> list() throws SQLException {
    List<User> users = new ArrayList<User>();

    try (
        Connection connection = database.getConnection();
        PreparedStatement statement = connection.prepareStatement("SELECT id, name, birthdate FROM User");
        ResultSet resultSet = statement.executeQuery();
    ) {
        while (resultSet.next()) {
            User user = new User();
            user.setId(resultSet.getLong("id"));
            user.setName(resultSet.getString("name"));
            user.setBirthdate(resultSet.getDate("birthdate"));
            users.add(user);
        }
    }

    return users;
}

Usage example - Servlet

In for example a Servlet class you can use it to transfer data from the database to the UI:

protected void doGet(HttpServletRequest request, HttpServletResponse response) {
    List<User> users = userDAO.list();
    request.setAttribute("users", users);
    request.getRequestDispatcher("/WEB-INF/users.jsp").forward(request, response);
}

Usage example - JSP

In for example a JSP page you can access it by EL, which follows the javabean conventions, to display the data:

<table>
    <tr>
        <th>ID</th>
        <th>Name</th>
        <th>Birthdate</th>
    </tr>
    <c:forEach items="${users}" var="user">
        <tr>
            <td>${user.id}</td>
            <td><c:out value="${user.name}" /></td>
            <td><fmt:formatDate value="${user.birthdate}" pattern="yyyy-MM-dd" /></td>
        </tr>
    </c:forEach>
</table>

(note: the <c:out> is just to prevent XSS holes while redisplaying user-controlled input as string)

Documentation

3994 questions
1
vote
0 answers

Spring repository in Swing

I have Swing application with Spring Boot and Spring Data JPA and without beans.xml (I use just annotations). So started normally. I used next annotations: @SpringBootApplication @ComponentScan("com.customerproject") @EnableAutoConfiguration public…
Leo
  • 97
  • 2
  • 12
1
vote
2 answers

Why can't IntelliJ IDEA resolve destroyMethod="close"?

I'm looking to add destroy-method = "close" to a bean, but IDEA 14 doesn't seem to like it. Anyone know why? Also tried "shutdown".
riddle_me_this
  • 8,575
  • 10
  • 55
  • 80
1
vote
0 answers

EJB JSF String[] cannot be cast to Datamodel

Im having trouble writing some feature in a huge EJB JSF Project: I need an Array of Strings shown in the GUI/html, works fine, but throws…
ahe
  • 128
  • 1
  • 9
1
vote
1 answer

Why is a dynamic created JSF EL value expression not resolved?

I got a simple setup (and a big issue): a JSP page with en empty panel grid item container and a binding to a bean. When the getter of the bean will be called, the container is filled…
Christian Smolka
  • 159
  • 1
  • 10
1
vote
1 answer

Stop MDB Message Redelivery

I've got a StatelessSessionBean, what, on calling a specific method, creates a MapMessage to be sent to an MDB. QueueConnection connection = null; QueueSession mSession = null; QueueSender messageProducer = null; try { QueueConnectionFactory…
Matthias Brück
  • 194
  • 1
  • 2
  • 12
1
vote
1 answer

Groovy: Setting property values easily

I have a map with name/value pairs: def myMap = [ "username" : "myname", "age" : 30, "zipcode" : 10010 ] I have a class called User defined: class User { def username; def age; def zipcode; } I would like to invoke the appropriate…
Tihom
  • 3,384
  • 6
  • 36
  • 47
1
vote
0 answers

How to correct the calling interval for a function with p:poll?

I'm developing an application that shows a clock to the user in order to control the execution time for tasks and log. The clock should have the server hour so it can't be modified by the user. The problem is that when the time runs, the…
Juan C
  • 89
  • 7
1
vote
1 answer

Java: Inject Singleton bean to test

I have a Singleton bean, and I have a Stateful bean too. I need to use the Singleton bean in the testclass of my Stateful bean. If I simply just inject it: @Inject private MySingletonBean mySingletonBean; I got null instead of the Stateful bean.…
Display Name
  • 1,121
  • 2
  • 11
  • 14
1
vote
2 answers

What java mapping libraries can map from a Map to pojo/bean?

Are there any mapping libraries (like Dozer) which can map from a Map to a pojo/bean? My specific use case is to map ScriptObjectMirrors coming out of nashorn, but I should be able to work at a higher interface since…
kag0
  • 5,624
  • 7
  • 34
  • 67
1
vote
1 answer

WELD-00143 Pseudo scoped bean has circular dependencies

Using WeldJUnit4Runner and getting error message: Exception 0 : org.jboss.weld.exceptions.DeploymentException: WELD-001443: Pseudo scoped bean has circular dependencies. Dependency path: - Managed Bean [class…
user840930
  • 5,214
  • 21
  • 65
  • 94
1
vote
1 answer

Tapestry5 - squash bean properties into one grid cell

i don't know if this is possible to do using Tapestry5. I would like to squash some bean properties into only one grid cell. For example, take a look at this bean : public class BeanExample { private int x; private int y; …
user6404301
1
vote
4 answers

Fix XmlBeanFactory Deprecated error Spring

These days I'm learning Spring Framework. And I'm following some youtube videos. According to the video I wrote my first code in Spring as same as the tutorial. But at a point I'm getting XmlBeanFactory deprecated warning which are not shown in…
user5099413
1
vote
2 answers

How to mock a file required by a Bean at initialization in JUnit tests

I have a Bean that is reading a file at initialization. The file is environment specific and is generated during the installation of the system. The path of the file is hardcoded as a final static variable in the code. private static final String…
iSpardz
  • 451
  • 4
  • 6
1
vote
2 answers

Unable to access Java Bean in Servlet, getAttribute() returns null

I am new to using Java Beans in Servlets and am having problem accessing a bean from a HttpServletRequest object. When I use getAttribute() it returns null. Here is my code: Station.jsp - JSP: