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
1 answer

remote connection dropped after some time in wildfly

I am using remote connection in java applet using the following code. Hashtable jndiProps = new Hashtable(); jndiProps.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory"); …
Sudipta Roy
  • 740
  • 1
  • 9
  • 29
1
vote
1 answer

Univocity: When using CsvRoutines to iterate beans, why can't I use iterator remove functionality?

Given I have setup the following iterator (with domain being some class and input being some file): BeanListProcessor beanProcessor = new BeanListProcessor>((Class>) domain); CsvParserSettings parserSettings = new…
Sander_M
  • 1,109
  • 2
  • 18
  • 36
1
vote
1 answer

Injecting blueprint bean into camel processor

please help me. How to inject bean declared in blueprint.xml to Camel processor? I am creating OSGI bundle for deployment in Jboss Fuse 6.1 container. My current blueprint.xml:
Maciavelli
  • 101
  • 1
  • 14
1
vote
1 answer

Set param value in first position of array bean

I want to know if is possible to set in a bean String Array a property received by an url parameter. I have this: The bean, in your FormHandler class: private String[] clientName; The JSP file:
Murcilha
  • 25
  • 9
1
vote
2 answers

Wildfly Transactions

My Wildfly server is running a copy method which takes 30 minutes to finish. For every copied item i got a log message. Ater 10 minutes the server is printing following message for around 20…
Dennis
  • 143
  • 5
  • 17
1
vote
2 answers

Creating two beans implementing the same interface

I want to create two bean implementing the same interface. Beans have names, but when I use @Qualifier annotation got error like: Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'cdPlayer'…
lassa
  • 173
  • 9
1
vote
1 answer

Why use XMLEncoder to serialize objects in java?

I understand that java objects can be serialized to a file, but under what circumstances would we need to use an XMLEncoder and serialize an object as XML? I'm starting to get a grip with Java EE and I understand that we can serialize beans using…
Coder
  • 101
  • 1
  • 1
  • 8
1
vote
1 answer

JSP JavaBean and Servlets?

I have to create a simple form that uses JSP for the view with the Model and the controller being Servlets, the communication needs to be done using JavaBeans. I've created a JSP powered form to accept a user name and a password which needs to be…
Kushan
  • 27
  • 1
  • 4
1
vote
3 answers

Struts2 - How to bind back the value to POJO which is rendered through on jsp page

I am working on Struts 2 and displaying a POJO/bean property value onto the JSP through tag. But when I submit back to the action, I am not getting this value binded to POJO. I am getting the values of…
CMG
  • 69
  • 6
1
vote
0 answers

Converting JSONObject to Java Bean

I'm interested in converting a JSONObject to a java bean. Let's say I have the following example code: public class Data { String name; String email; String age; String favoriteHobby; } JSONObject response = {'name' : 'alex',…
Alex Cauthen
  • 497
  • 5
  • 12
  • 32
1
vote
2 answers

Xpages runtime interpreting java package name as String object

From all the weirdness in our current Xpages project this one currently hits the ceiling: we have created a few java beans in our current project. Inside Domino Designer they all are stored below Code >> Java, so that it is clear that they are…
Lothar Mueller
  • 2,528
  • 1
  • 16
  • 29
1
vote
0 answers

Generate beans xml at compilation spring

I found this: Component scan issue Component scan time too long Component scan is too low I am trying to load an application (approximatively 200M). Our application just contains 265 beans. However we have runtime dependencies which bring thousands…
Geoffrey
  • 1,151
  • 3
  • 13
  • 26
1
vote
1 answer

Which way of specifiying my beans in spring-integration.xml is better?

I have two different ways of declaring a spring integration bean. They both seem to work. I'm using the Spring STS Eclipse based IDE. This way:
Gabriel Fair
  • 4,081
  • 5
  • 33
  • 54
1
vote
1 answer

How to use @Service annotated class as an @Autowired bean in another class which is outside the component scan package of the Service class?

I have a service interface called ABCService and its implementation called ABCServiceImpl. ABCService.class package com.abc.service.ABCService; public interface ABCService{ //interface methods } ABCServiceImpl.class package…
Akash Raveendran
  • 559
  • 1
  • 9
  • 22
1
vote
1 answer

Deep copy between different class name with same fields + Java

I have two objects with name Site and AppSite, both has same fields like below. Is there any util class to copy all the fields from AppSite to Site, like BeanUtils.copyProperties. public class AmsSite implements Serializable{ private long…
Mohan
  • 699
  • 1
  • 11
  • 27
1 2 3
99
100