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

Accessing Spring beans from servlet filters and tags

I can access Spring beans in my Servlets using WebApplicationContext springContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext()); in the Servlet's init method. I was wondering is there an equivalent of the…
Damien
  • 4,081
  • 12
  • 75
  • 126
25
votes
5 answers

javabean vs servlet

I was searching for difference between javabean and servlet. I found Servlet corresponds a Controller JavaBean corresponds a Model and java bean is a reusable component,where as the servlet is the java program which extends the server…
Ravi
  • 30,829
  • 42
  • 119
  • 173
24
votes
3 answers

BeanUtils.cloneBean() deep copy

If all the objects within the bean implement Serializable interface, will BeanUtils.cloneBean() do a deep copy?
hop
  • 2,518
  • 11
  • 40
  • 56
23
votes
17 answers

Word Wrap in Net Beans

Netbeans is great but there's no way to wrap text in it (or hopefully I haven't found it yet). Is there any way to do this, and if not, is there any similarly good IDE for Java with this functionality (hopefully free as well).
Java guy
23
votes
1 answer

JavaBean wrapping with JavaFX Properties

I want to use JavaFX properties for UI binding, but I don't want them in my model classes (see Using javafx.beans properties in model classes). My model classes have getters and setters, and I want to create properties based on those. For example,…
warakawa
  • 628
  • 1
  • 7
  • 14
22
votes
4 answers

find out the differences between two java beans for version tracking

say i have a java bean/an entity with 100 fields (inherited or not it is not relevant in this case). After update operations - in a transaction, i want to determine which fields are modified to track updates like a CVS. What is the easiest way to do…
Erhan Bagdemir
  • 5,231
  • 6
  • 34
  • 40
22
votes
4 answers

.dll already loaded in another classloader?

I have a webapp running under Tomcat 3.2.1 that needs to make JNI calls in order to access data and methods in legacy C++ code. A servlet is loaded on startup of the webapp that, as part of its init method, causes a data set specific to that webapp…
krishnakumar
  • 2,187
  • 5
  • 21
  • 24
21
votes
2 answers

difference between java bean and java class?

I am new to the JSP and server side programming. Till now I am working with Servlets and java classes. I am segregating my application (as per MVC model) with the help of java classes. I would like to know difference between java beans and java…
Raj
  • 2,463
  • 10
  • 36
  • 52
21
votes
4 answers

how to generically compare entire java beans?

I've been trying to grok the org.apache.commons.beanutils library for a method/idiom to evaluate for equality all properties between 2 instances i.e. a generic equals() method for beans. Is there a simple way to do this usnig this library? Or am I…
ysouter
  • 213
  • 1
  • 2
  • 4
21
votes
4 answers

Spring Bean property 'xxx' is not writable or has an invalid setter method

I'm a Spring newbie with a seemingly simple Spring problem. I worked on this for hours without luck. Here is the exception, followed by the code (thank you in advance): Exception in thread "main"…
NYCeyes
  • 5,215
  • 6
  • 57
  • 64
21
votes
2 answers

Where is the JavaBean property naming convention defined?

The Spring Framework API doc says: The convention used is to return the uncapitalized short name of the Class, according to JavaBeans property naming rules: So, com.myapp.Product becomes product; com.myapp.MyProduct becomes myProduct;…
deamon
  • 89,107
  • 111
  • 320
  • 448
20
votes
2 answers

Java EE 6 : @Inject and Instance

I have a question about the @Inject annotation in java ee 6 : What is the difference between : @Inject private TestBean test; @Inject private Instance test2; To have the reference : test2.get(); Some infos about Instance :…
jihedMaster
  • 331
  • 1
  • 3
  • 11
20
votes
2 answers

How to set Class value to spring bean property?

Hey, what is the best way to set a bean's property with Class value ? Regarding XML configuration. For a bean like this : public class FilterJsonView extends MappingJacksonJsonView { private Set filteredAttributes; private Class…
lisak
  • 21,611
  • 40
  • 152
  • 243
20
votes
4 answers

Declaring an array of objects in a Spring bean context

I'm trying to create an array of objects in a Spring context file so I can inject it to a constructor that's declared like this: public RandomGeocodingService(GeocodingService... services) { } I'm trying to use the tag:
Alex Ciminian
  • 11,398
  • 15
  • 60
  • 94
20
votes
3 answers

Difference among Model, javabean and POJO

I started learning MVC with spring. I have heard lot of time Bean, that contains setter and getter. Model is basically what data flows around, and Pojo which is same as Bean. But I am really confused in all this term and all this look same to me can…
Varun
  • 4,342
  • 19
  • 84
  • 119