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
17
votes
3 answers

Java Beans, BeanUtils, and the Boolean wrapper class

I'm using BeanUtils to manipulate Java objects created via JAXB, and I've run into an interesting issue. Sometimes, JAXB will create a Java object like this: public class Bean { protected Boolean happy; public Boolean isHappy() { …
17
votes
8 answers

List> to org.json.JSONObject?

List> list = new ArrayList>(); Map map = new HashMap(); map.put("abc", "123456"); map.put("def", "hmm"); list.add(map); JSONObject json = new JSONObject(list); try { …
yogman
  • 4,021
  • 4
  • 24
  • 27
17
votes
2 answers

@ManagedProperty(value = "#{param.id}") in a non-request Scope Bean

I need to pass a parameter (POST) to a @managedBean, I used managed properties like this: @ManagedProperty(value = "#{param.id}") private int id; And the scope of the Bean is ViewScope I end up with this error: Unable to create managed bean…
ehsun7b
  • 4,796
  • 14
  • 59
  • 98
17
votes
5 answers

use @autowired in abstract base class

As I know, field injection is not recommended. Should use constructor instead. What I'm trying to do here is using @Autowired in the constructor of the base class, and make it accessible for all the subclasses. In some subclasses, I also need some…
Vigor
  • 1,706
  • 3
  • 26
  • 47
17
votes
3 answers

Java 8 interface default method doesn't seem to declare property

In my application I run into a problem that when a getter in a class is defaulted in an interface only (Java 8 feature), there is no Java Beans property as a result. I.e. for normal method invocation it works just as a standard method, but for…
user319799
17
votes
1 answer

Difference between SimpleStringProperty and StringProperty

I am working with JavaFx TableView and found there are some classes to use a TableView for example SimpleStringProperty, StringProperty, SimpleBooleanProperty and BooleanProperty, etc. Now I am wondering about which one to use for TableView either…
Biswadip Dey
  • 509
  • 2
  • 7
  • 20
16
votes
2 answers

Using a Stateful Session Bean to track an user's session

it's my first question here and I hope that I'm doing it right. I need to work on a Java EE project, so, before starting, I'm trying to do something simple and see if I can do that. I'm stuck with Stateful Session Beans. Here's the question : How…
StepTNT
  • 3,867
  • 7
  • 41
  • 82
16
votes
1 answer

@PreDestroy never called on @ViewScoped

I have a @ViewScoped bean that has a method with an @PreDestroy annotation that should make sure some remote connections are closed. However, the method is not called when the user navigates away. Is there anything one can do wrong? Do I have to…
geeehhdaa
  • 822
  • 5
  • 17
  • 30
16
votes
1 answer

How to perform validation in JSF, how to create a custom validator in JSF

I would like to perform validation in some of my input components such as using some Java bean method. Should I use or for this? Where can I read more about it?
Aram Gevorgyan
  • 2,175
  • 7
  • 37
  • 57
16
votes
6 answers

bean of type 'org.springframework.http.codec.ServerCodecConfigurer' that could not be found

APPLICATION FAILED TO START Description: Parameter 0 of method modifyRequestBodyGatewayFilterFactory in org.springframework.cloud.gateway.config.GatewayAutoConfiguration required a bean of type 'org.springframework.http.codec.ServerCodecConfigurer'…
16
votes
1 answer

Keeping track of changed properties in JPA

Currently, I'm working on a Java EE project with some non-trivial requirements regarding persistence management. Changes to entities by users first need to be applied to some working copy before being validated, after which they are applied to the…
G_H
  • 11,739
  • 3
  • 38
  • 82
16
votes
4 answers

JSF Managed Bean auto-create?

Is it possible to have a JSF managed bean be automatically created? For example I have several session scoped beans. Sometimes it becomes necessary to access these instances in code (rather than just in JSF) this is done by: PageBean pageBean =…
rat
  • 2,544
  • 5
  • 21
  • 19
15
votes
2 answers

"@inject"-ed attribute remains null

I am trying to inject a service into my bean but it is always null. I get the following error: WELD-001000 Error resolving property userBean against base null. Some code snippets: index.xhtml Hello from Facelets …
martijnve
  • 993
  • 2
  • 9
  • 23
15
votes
3 answers

Spring beans DTD and XMLNS

When i am creating a spring project I always have problem with XLMNS. what is exactly XMLNS? what are these actually?
user962206
  • 15,637
  • 61
  • 177
  • 270
15
votes
4 answers

Copying one class's fields into another class's identical fields

I have this question. But it will be difficult for me to explain as I don't know exact terms to use. Hope someone will understand. I'll try to discribe to the best i can. I feel like this is much related to parsing Say there are two classes. And in…
Anubis
  • 6,995
  • 14
  • 56
  • 87