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
0 answers

A platform to run Runnable objects

I am trying to create a platform for clients to run their Runnable objects at a specified rate endlessly. I have the following code: public class Health { public Health(Runnable r, int rate) { // I want to fork a new thread and then…
User_Targaryen
  • 4,125
  • 4
  • 30
  • 51
1
vote
1 answer

How to display nested objects with JavaBeans as datasource?

Here is my java objects : Class1.java : public class Class1 { public Class2 object2; ... } Class2.java : public class Class2 { public Class3 object3; ... } Class3.java : public class Class3 { public List list4; …
Sinda MOKADDEM
  • 796
  • 2
  • 12
  • 35
1
vote
1 answer

Java - Add custom event Listener to a eventSet in beanInfo with Netbeans

i have a custom bean and a custom eventListener, i need to show my event Listener in the events tab of my bean. I think the solution is to add my event Listener to a beaninfo(i create it with netbeans, so it is auto-generated). There is a…
blow
  • 12,811
  • 24
  • 75
  • 112
1
vote
2 answers

Xpages: How to access database from CacheBean

I have a cacheBean called PCConfig in which I want to store references to databases, so I can access them in other Java methods. Here is the relevant part of my cacheBean: package com.scoular.cache; import java.io.Serializable; import…
Bryan Schmiedeler
  • 2,977
  • 6
  • 35
  • 74
1
vote
1 answer

Setting default values in Java Beans / Data transfer Objects

We use Data Transfer Objects (DTO) in our code. When constructing them, it is inevitable that some of their fields will have null values as some of those fields are null in the database. We were told that all null values must be default to "NA". I…
1
vote
0 answers

opencsv not mapping values to javabean

I´m new to OpenCSV here and I´m trying to parse a CSV file received in a REST service. Here´s my code: CSVReader csvReader = new CSVReader(new InputStreamReader(csv), ';', CSVParser.DEFAULT_QUOTE_CHARACTER); …
Rafael Barioni
  • 183
  • 1
  • 1
  • 12
1
vote
1 answer

SnakeYAML: How to set bean property type for loading

Using SnakeYAML's TypeDescription, I can add type information about Lists and Maps using: TypeDescription td = new TypeDescription(MyBean.class, "!mybean"); td.putMapPropertyType("mymap", String.class,…
dbt
  • 73
  • 1
  • 7
1
vote
1 answer

Accessing parent class when doing custom converter

I am currently using Dozer to map to sets of objects. I have a situation where I need to use a custom converter to map a String to TypeA. The way I convert TypeA to a String depends on the type of Object TypeA is a member of. Specifically TypeA has…
ballmw
  • 945
  • 7
  • 13
1
vote
1 answer

NoSuchBeanDefinitionException: No qualifying bean

I have an error in Spring mvc: (org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'webController': Injection of autowired dependencies failed; nested exception is…
Nick Nick
  • 177
  • 3
  • 18
1
vote
1 answer

Jasper Reports doesn't composite DataBean

I want to map my DataBean(TestModelA) to existing XML, but JasperReports gives me an exception. The problem is that I have custom field (TestModelB) and I have public getters and setters in that class, but jasper does not recognize them. How can i…
1
vote
1 answer

In JSP represent a field built from other fields in a bean

I am working on a Java project using Spring MVC framework and JSP for my views. I'm wondering about how best to represent fields that are derived from properties in the bean I'm using as a model attribute. In my example a DisplayName field that is…
Luke
  • 1,218
  • 1
  • 24
  • 40
1
vote
0 answers

How to define protected, public and private in Generic JavaBean?

I am wondering how can I define protected, public and private properties in my class GenericBean, which will result in a JavaBean. So far I've declared a class, that will enable use to access the value of the Bean, however, I have no idea how I can…
alegrowski
  • 261
  • 2
  • 3
  • 8
1
vote
1 answer

Spring Beans Configurations

if we have 1- a case scenario where we have class A configured as singleton and a child class B as a member within Class A configured as prototype. 2- Another case scenario, which is the opposite to the first one, where we have Class A defined as…
1
vote
1 answer

Spring set bean name with @Named

I use javax standard annotation @Named for defining beans in spring4. To set the bean name I could tried @Named("MyBean") but it did not change the bean name. I used spring Component annotation @Component("MyBean") and it worked fine. Is it possible…
Alireza Fattahi
  • 42,517
  • 14
  • 123
  • 173
1
vote
0 answers

Does Java have a class for Java Bean standard handling?

Does Java natively have a class for Java Bean standard handling? Say, I want to pass the field name and instance and get the getter, or setter, or value?
Daniel Calderon Mori
  • 5,466
  • 6
  • 26
  • 36
1 2 3
99
100