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
59
votes
13 answers

Json <-> Java serialization that works with GWT

I am looking for a simple Json (de)serializer for Java that might work with GWT. I have googled a bit and found some solutions that either require annotate every member or define useless interfaces. Quite a boring. Why don't we have something really…
amartynov
  • 4,125
  • 2
  • 31
  • 35
50
votes
6 answers

Java Spring bean with private constructor

Is possible in Spring that class for bean doesn't have public constructor but only private ? Will this private constructor invoked when bean is created? Thanks.
user710818
  • 23,228
  • 58
  • 149
  • 207
50
votes
2 answers

JPA 2.0 : Exception to use javax.validation.* package in JPA 2.0

when i try to using bean validation with JPA using hibernate , the follwoing exception will occur : Exception in thread "main" javax.persistence.PersistenceException: [PersistenceUnit: Chapter11] Unable to build EntityManagerFactory at…
Harmeet Singh Taara
  • 6,483
  • 20
  • 73
  • 126
45
votes
6 answers

how to reference a bean of another xml file in spring

I have a Spring bean defined in an xml file. I want to reference it from another xml file. How can I go about it?
Jeffrey.W.Dong
  • 1,057
  • 3
  • 14
  • 21
44
votes
4 answers

Difference between Java Bean and Enterprise Java Beans?

Are they different or they are used interchangeably? If they are Different, then what made them different from each other?
GuruKulki
  • 25,776
  • 50
  • 140
  • 201
43
votes
4 answers

What is a Java bean?

Possible Duplicate: What's the point of beans? What is a javabean? What is it used for? And what are some code examples? I heard it is used for something to do with getter and setter methods? I'm quite confused about what a java bean is and where…
Ryan Glenn
  • 1,325
  • 4
  • 17
  • 30
42
votes
11 answers

Java Interface Usage Guidelines -- Are getters and setters in an interface bad?

What do people think of the best guidelines to use in an interface? What should and shouldn't go into an interface? I've heard people say that, as a general rule, an interface must only define behavior and not state. Does this mean that an…
His
  • 5,891
  • 15
  • 61
  • 82
41
votes
6 answers

What is a "Java Bean"?

The name really throws me off. I'm hoping someone can explain it in a way I won't forget :)
mrblah
  • 99,669
  • 140
  • 310
  • 420
41
votes
5 answers

Difference between Javabean and EJB

Just a simple question from a relative Java newbie: what is the difference between a JavaBean and an EJB?
LRE
  • 956
  • 1
  • 10
  • 15
38
votes
7 answers

Naming convention for getters/setters in Java

if I have the following private member: private int xIndex; How should I name my getter/setter: getXindex() setXindex(int value) or getxIndex() setxIndex(int value) EDIT: or getXIndex() setXIndex(int value); ?
Simon
  • 9,255
  • 4
  • 37
  • 54
36
votes
3 answers

Create prototype scoped Spring bean with annotations?

Is it possible to convert the following XML configuration to an annotation based one? I'm using Spring 2.5.6.
user321068
36
votes
5 answers

Java PMD warning on non-transient class member

On line: private boolean someFlag; I get the following PMD warning: Found non-transient, non-static member. Please mark as transient or provide accessors. Can someone please explain why this warning is there and what it means? (I understand how…
Yuval Adam
  • 161,610
  • 92
  • 305
  • 395
36
votes
1 answer

How to get the id of a bean from inside the bean in Spring?

What is the easiest way to retrieve a bean id from inside that bean (in the Java code) without using a BeanPostProcessor to set a field? The only way I can think of is something like this using a BeanPostProcessor: public Object…
user21037
35
votes
4 answers

How to copy properties from a bean to another bean in different class?

I have two java class with same properties names.How Can I copy all the properties to another bean filled with data.I don't want to use the traditional form to copy properties because I have a lot of properties. Thanks in advance. 1 class…
user2683519
  • 747
  • 5
  • 11
  • 19
33
votes
2 answers

ArrayOutOfBoundsException on Bean creation while using Java 8 constructs

I am getting an ArrayIndexOutOfBoundsException on service start up (Bean creation) when i use Java 8 features. Java 8 has been set up and has been working. The code compiles correctly. On service start, the service fails to listen to port as the…
akshitBhatia
  • 1,131
  • 5
  • 12
  • 20