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
2327
votes
23 answers

What is a JavaBean exactly?

I understood, I think, that a "Bean" is a Java-class with properties and getters/setters. As much as I understand, it is the equivalent of a C struct. Is that true? Also, is there a real syntactic difference between a JavaBean and a regular class?…
677
votes
8 answers

Difference between DTO, VO, POJO, JavaBeans?

Have seen some similar questions: What is the difference between a JavaBean and a POJO? What is the Difference Between POJO (Plain Old Java Object) and DTO (Data Transfer Object)? Can you also please tell me the contexts in which they are used? Or…
jai
  • 21,519
  • 31
  • 89
  • 120
234
votes
11 answers

For a boolean field, what is the naming convention for its getter/setter?

Eg. boolean isCurrent = false; What do you name its getter and setter?
user496949
  • 83,087
  • 147
  • 309
  • 426
203
votes
4 answers

Places where JavaBeans are used?

What is a JavaBean and why do I need it? Since I can create all apps with the class and interface structure? Why do I need beans? And can you give me some examples where beans are essential instead of classes and interfaces? Please explain the…
Sidharth
  • 3,629
  • 7
  • 26
  • 22
184
votes
1 answer

DTO and DAO concepts and MVC

Why do we use DTO and DAO, and when should we use them. I am developing a GUI Java software to do with inserting, editing, deleting data. But I am struggling to distinguish between DTO/DAO and Model, View, Controller (MVC) structure? Are they…
Hoody
  • 2,942
  • 5
  • 28
  • 32
113
votes
3 answers

What is java pojo class, java bean, normal class?

Possible Duplicate: Difference between DTO, VO, POJO, JavaBeans? Hi please don't say my question is duplicate :-) I saw all questions but didn't understand the exact difference. Can someone explain what is POJO, Bean, Normal Class in easy…
Siva
  • 3,297
  • 7
  • 29
  • 35
112
votes
5 answers

Can I update a JSF component from a JSF backing bean method?

Is there a way to have a JSF Backing bean cause an update of a component on the page? I am not looking to use an ajax component with update attribute to update a component on the page. I need to trigger an update from within a JSF backing bean…
BestPractices
  • 12,738
  • 29
  • 96
  • 140
103
votes
24 answers

How to convert a Java object (bean) to key-value pairs (and vice versa)?

Say I have a very simple java object that only has some getXXX and setXXX properties. This object is used only to handle values, basically a record or a type-safe (and performant) map. I often need to covert this object to key value pairs (either…
Shahbaz
  • 10,395
  • 21
  • 54
  • 83
87
votes
7 answers

Programmatically configure LogBack appender

I have a logback appender defined in the logback.xml, it's a DB appender, but I'm curious if there is any way to configure the appender in java using my own connection pool defined as a bean. I find similar things, but never the actual answer.
user1732480
85
votes
24 answers

Spring cannot find bean xml configuration file when it does exist

I am trying to make my first bean in Spring but got a problem with loading a context. I have a configuration XML file of the bean in src/main/resources. I receive the following IOException: Exception in thread "main" …
dawrutowicz
  • 2,930
  • 2
  • 15
  • 19
83
votes
5 answers

Spring - using static final fields (constants) for bean initialization

is it possible to define a bean with the use of static final fields of CoreProtocolPNames class like this:
lisak
  • 21,611
  • 40
  • 152
  • 243
80
votes
7 answers

Why shouldn't I use immutable POJOs instead of JavaBeans?

I have implemented a few Java applications now, only desktop applications so far. I prefer to use immutable objects for passing the data around in the application instead of using objects with mutators (setters and getters), also called…
Jonas
  • 121,568
  • 97
  • 310
  • 388
68
votes
3 answers

Valid JavaBeans names for boolean getter methods

I know most variable names will work with "is", such as isBlue(), but is "has" also a valid prefix, like hasProperty()?
Robert
62
votes
11 answers

Difference between managed bean and backing bean

I came across the terms "managed bean" and "backing bean" in several forums. Many people think both are the same. But, there seems to be a slight difference. Can any one help me to understand the exact difference between these two terms?
Krishna
  • 7,154
  • 16
  • 68
  • 80
60
votes
4 answers

Difference between JavaBean and Spring bean

I am new to Spring MVC and have a little idea of the usage of java beans in Java. What is the basic difference between a Java bean and Spring bean?
Arpit Shah
  • 2,159
  • 2
  • 14
  • 9
1
2 3
99 100