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
12
votes
2 answers

Flattening Java Bean to a Map

I am stuck at converting Java Bean to Map. There are many resources on the internet, but unfortunately they all treat converting simple beans to Maps. My ones are a little bit more extensive. There's simplified example: public class MyBean { …
Maciej Dobrowolski
  • 11,561
  • 5
  • 45
  • 67
12
votes
2 answers

Logging Spring bean initialization with Log4J

When I run my application, it stops when beans are initializing but doesn't show any logs entries. So I don't know what happened: Log4j.properties log4j.rootLogger=DEBUG, stdout,…
Mateusz
  • 205
  • 1
  • 4
  • 11
12
votes
4 answers

How do I print a list of strings contained within another list in iReport?

I am creating a simple reporting program using java and iReport (from jasper), which is supposed to create a report in pdf showing PCs with their IP address, their location, whether it's idle or not at the moment (handled by another system), and a…
Kenji Kina
  • 2,402
  • 3
  • 22
  • 39
12
votes
1 answer

boolean properties starting with "is" does not work

I have a project that use JSF 2.1 and PrimeFaces. I tried to use a simple referencing #{myBean.matriz} and I got this error: SEVERE: javax.el.PropertyNotFoundException: ... value="#{myBean.matriz}": Missing Resource in EL…
andolffer.joseph
  • 613
  • 2
  • 10
  • 24
12
votes
3 answers

Replace spring bean in one context with mock version from another context

I'm writing an integration test where an application context xml is initialized during startup. There are several test methods in the test class which make use of a specific bean 'X'(already defined in the xml). My actual requirement is to mock bean…
Ram
  • 191
  • 1
  • 2
  • 12
12
votes
1 answer

Gson force use int instead of double

Hi can i configure gson that he use int instead of double got data like: {fn: chat, data: {roomId: 1, text: "Some brabble"}} I got a PacketClass to deserialize it to: public class DataPacket { private String fn; private Object p; // will be a…
Kani
  • 810
  • 1
  • 19
  • 38
11
votes
1 answer

@Singleton in Java EJB

I have an EJB that needs to be a singleton and stateful since it's going to be a sort of connection pool. My questions are: If I define an EJB with @Singleton annotation, will it then be stateful by default or do I have to define it with @Stateful…
Marthin
  • 6,413
  • 15
  • 58
  • 95
11
votes
3 answers

load spring bean into a servlet

There are many documentations out there on how to achieve this task but I still couldn't resolve my issue. I'm new to working with servlet so I probably missed something. I use red5 that uses tomcat 6 to create a servlet that uses a spring bean…
ufk
  • 30,912
  • 70
  • 235
  • 386
11
votes
1 answer

Spring session-scoped beans as dependencies in prototype beans?

I read spring docs on this subject several times, but some things are still unclear to me. Documentation states: If you want to inject (for example) an HTTP request scoped bean into another bean, you must inject an AOP proxy in place of the scoped…
Less
  • 3,047
  • 3
  • 35
  • 46
11
votes
11 answers

JavaBeans alternatives?

I hate the JavaBeans pattern with a passion that burns like the fire of a thousand suns. Why? Verbose. It's 2009. I shouldn't have to write 7 LOC for a property. If they have event listeners then hold on to your hat. No type-safe references. There…
SamBeran
  • 1,944
  • 2
  • 17
  • 24
11
votes
2 answers

Spring java config - create list of beans also created in runtime

I have a list of gaming rooms which is created by Spring. Each rooms corresponds some rules (which is enum), and the code is: @Bean List rooms() { return Arrays.stream(Rules.values()) .map(rule -> new Room(rule)) …
awfun
  • 2,316
  • 4
  • 31
  • 52
11
votes
3 answers

Scala Properties Question

I'm still learning Scala, but one thing I thought was interesting is that Scala blurs the line between methods and fields. For instance, I can build a class like this... class MutableNumber(var value: Int) The key here is that the var in the…
shj
  • 1,558
  • 17
  • 23
11
votes
3 answers

Spring: Bean property not writable or has an invalid setter method

I'm experimenting with Spring, I'm following the book: Spring: A developer's notebook. I'm getting this error: "Bean property 'storeName' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type…
Krt_Malta
  • 9,265
  • 18
  • 53
  • 91
11
votes
1 answer

Add custom data source to Jaspersoft Studio

I am trying to fill a table by passing a custom data source to it. I have created a simple report with a table on it. The report it self gets the data from a ms sql database. I have written a java class similar to the class in this Example. But I…
Iman
  • 769
  • 1
  • 13
  • 51
11
votes
1 answer

Convert String to Enum using Apache BeanUtils

I've implemented a converter for Apache BeanUtils library for converting String to an enum constant: class EnumConverter implements Converter { @Override public T convert(Class tClass, Object o) { String enumValName =…
Ivan Mushketyk
  • 8,107
  • 7
  • 50
  • 67