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
15
votes
4 answers

Why did PropertyDescriptor behavior change from Java 1.6 to 1.7?

Update: Oracle has confirmed this as a bug. Summary: Certain custom BeanInfos and PropertyDescriptors that work in JDK 1.6 fail in JDK 1.7, and some only fail after Garbage Collection has run and cleared certain SoftReferences. Edit: This will also…
jbindel
  • 5,535
  • 2
  • 25
  • 38
15
votes
4 answers

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'customerService' is defined

I need help fixing this error I get when trying to deploy my web application into tomcat. Why isn't the customerService bean being defined? Am I missing something in my web.xml or do I have to map the customerService somehow? I am using annotations…
dlinx90
  • 855
  • 4
  • 14
  • 24
14
votes
8 answers

How to copy properties from one Java bean to another?

I have a simple Java POJO that I would copy properties to another instance of same POJO class. I know I can do that with BeanUtils.copyProperties() but I would like to avoid use of a third-party library. So, how to do that simply, the proper and…
paulgreg
  • 18,493
  • 18
  • 46
  • 56
14
votes
1 answer

JGoodies Binding vs. JSR 295

What is the practical difference between JGoodies Binding and JSR 295, Beans Binding? They both seem to be intended for the same purpose and get their job done (with slightly different approaches). JGoodies Binding is more mature, but JSR 295 is…
Joonas Pulakka
  • 36,252
  • 29
  • 106
  • 169
14
votes
2 answers

How are beans named by default when created with annotation?

I am working with Spring java code written by someone else. I want to reference a bean that's created by annotation (of field classABC): @Component public class ClassService { @Autowired ClassABC classABC; public interface…
DSimkin
  • 165
  • 1
  • 1
  • 8
14
votes
2 answers

How to declare an optional @Bean in Spring?

I want to provide an optional @Bean in my @Configuration file like: @Bean public Type method(Type dependency) { // TODO } when dependency can't be found, the method should not be called. How to do that?
Elderry
  • 1,902
  • 5
  • 31
  • 45
14
votes
13 answers

Assert that two java beans are equivalent

This question is close, but still not what I want. I'd like to assert in a generic way that two bean objects are equivalent. In case they are not, I'd like a detailed error message explaining the difference instead of a boolean "equal" or "not…
ripper234
  • 222,824
  • 274
  • 634
  • 905
14
votes
3 answers

How to Define a MySql datasource bean via XML in Spring

I've looked over the documentation to define a bean. I'm just unclear on what class file to use for a Mysql database. Can anyone fill in the bean definition below?
cyotee doge
  • 1,128
  • 4
  • 15
  • 33
13
votes
1 answer

JasperReports: How to call a java bean method in report template?

I am passing a java bean collection into a jasper report. I have several fields for this java bean defined an they are display just fine in my report. Im wondering if there is a way to call a method of a java bean that is being passed into this…
tinny
  • 4,232
  • 7
  • 28
  • 38
13
votes
2 answers

How to convert spring bean integration From XML to Java annotation based Config

I have this xml based configuration. But in my project I want to use java annotation based configuration. How to do the conversion?
sndu
  • 933
  • 4
  • 14
  • 40
13
votes
1 answer

dynamically create class in scala, should I use interpreter?

I want to create a class at run-time in Scala. For now, just consider a simple case where I want to make the equivalent of a java bean with some attributes, I only know these attributes at run time. How can I create the scala class? I am willing to…
Phil
  • 46,436
  • 33
  • 110
  • 175
13
votes
1 answer

JavaFX Beans Binding suddenly stops working

I use JavaFX NumberBindings in order to calculate certain values. Initially everything works as expected. After a rather small amount of time, however, the binding just stops working. I don't receive an Exception, either. I've tried several…
underkuerbis
  • 325
  • 3
  • 9
13
votes
4 answers

Complex Bean Mapping

I am trying to find the best solution for a problem I have with mapping a simple bean structure that is being sent to a browser-based JavaScript application. The current requirement is to manage most of the display control on the old Java backend.…
rock-fall
  • 438
  • 2
  • 11
12
votes
4 answers

Java date and calendar controls

Does anybody have any recommendations of good date pickers (either drop down calendars or small calendar components) for use in a Java Swing application - either beans or source code? They need to be robust enough for commercial applications.
Miles D
  • 7,960
  • 5
  • 34
  • 35
12
votes
7 answers

What is an Enterprise Java Bean really?

On the Tomcat FAQ it says: "Tomcat is not an EJB server. Tomcat is not a full J2EE server." But if I: use Spring to supply an application context annotate my entities with JPA annotations (and use Hibernate as a JPA provider) configure C3P0 as a…
Dave
  • 21,524
  • 28
  • 141
  • 221