How to create a POJO?

JavaPojo

Java Problem Overview


Recently I've started hearing about "POJOs" (Plain Old Java Objects). I googled it, but still don't understand the concept well. Can anyone give me a clear description of a POJO?

Consider a class "Person" with variables "id, name, address, salary" -- how would I create a POJO for this scenario? Is the code below a POJO?

public class Person {
    //variables
    People people = new People();
    private int id;
    private String name;
    private String address;
    private int salary;


    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getAddress() {
        return address;
    }

    public int getSalary() {
        return salary;
    }

    public void setId() {
        this.id = id;
    }

    public void setName() {
        this.name = name;
    }

    public void setAddress() {
        this.address = address;
    }

    public void setSalary() {
        this.salary = salary;
    }
}

Java Solutions


Solution 1 - Java

A POJO is just a plain, old Java Bean with the restrictions removed. Java Beans must meet the following requirements:

  1. Default no-arg constructor
  2. Follow the Bean convention of getFoo (or isFoo for booleans) and setFoo methods for a mutable attribute named foo; leave off the setFoo if foo is immutable.
  3. Must implement java.io.Serializable

POJO does not mandate any of these. It's just what the name says: an object that compiles under JDK can be considered a Plain Old Java Object. No app server, no base classes, no interfaces required to use.

The acronym POJO was a reaction against EJB 2.0, which required several interfaces, extended base classes, and lots of methods just to do simple things. Some people, Rod Johnson and Martin Fowler among them, rebelled against the complexity and sought a way to implement enterprise scale solutions without having to write EJBs.

Martin Fowler coined a new acronym.

Rod Johnson wrote "J2EE Without EJBs", wrote Spring, influenced EJB enough so version 3.1 looks a great deal like Spring and Hibernate, and got a sweet IPO from VMWare out of it.

Here's an example that you can wrap your head around:

public class MyFirstPojo
{
    private String name;

    public static void main(String [] args)
    {
       for (String arg : args)
       {
          MyFirstPojo pojo = new MyFirstPojo(arg);  // Here's how you create a POJO
          System.out.println(pojo); 
       }
    }

    public MyFirstPojo(String name)
    {    
        this.name = name;
    }

    public String getName() { return this.name; } 

    public String toString() { return this.name; } 
}

Solution 2 - Java

POJO:- POJO is a Java object not bound by any restriction other than those forced by the Java Language Specification.

Properties of POJO

  1. All properties must be public setter and getter methods
  2. All instance variables should be private
  3. Should not Extend prespecified classes.
  4. Should not Implement prespecified interfaces.
  5. Should not contain prespecified annotations.
  6. It may not have any argument constructors

Example of POJO

public class POJO {
 
    private String value;
 
    public String getValue() {
         return value;
    }
 
    public void setValue(String value) {
        this.value = value;
    }
}

Solution 3 - Java

A POJO is a Plain Old Java Object.

From the wikipedia article I linked to:

> In computing software, POJO is an > acronym for Plain Old Java Object. The > name is used to emphasize that a given > object is an ordinary Java Object, not > a special object, and in particular > not an Enterprise JavaBean

Your class appears to already be a POJO.

Solution 4 - Java

POJO class acts as a bean which is used to set and get the value.

public class Data
{


private int id;
	private String deptname;
	private String date;
	private String name;
	private String mdate;
	private String mname;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getDeptname() {
		return deptname;
	}

	public void setDeptname(String deptname) {
		this.deptname = deptname;
	}

	public String getDate() {
		return date;
	}

	public void setDate(String date) {
		this.date = date;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getMdate() {
		return mdate;
	}

	public void setMdate(String mdate) {
		this.mdate = mdate;
	}

	public String getMname() {
		return mname;
	}

	public void setMname(String mname) {
		this.mname = mname;
	}
}

Solution 5 - Java

When you aren't doing anything to make your class particularly designed to work with a given framework, ORM, or other system that needs a special sort of class, you have a Plain Old Java Object, or POJO.

Ironically, one of the reasons for coining the term is that people were avoiding them in cases where they were sensible and some people concluded that this was because they didn't have a fancy name. Ironic, because your question demonstrates that the approach worked.

Compare the older POD "Plain Old Data" to mean a C++ class that doesn't do anything a C struct couldn't do (more or less, non-virtual members that aren't destructors or trivial constructors don't stop it being considered POD), and the newer (and more directly comparable) POCO "Plain Old CLR Object" in .NET.

Solution 6 - Java

According to Martin Fowler

>The term was coined while Rebecca Parsons, Josh MacKenzie and I were preparing for a talk at a conference in September 2000. In the talk, we were pointing out the many benefits of encoding business logic into regular java objects rather than using Entity Beans. We wondered why people were so against using regular objects in their systems and concluded that it was because simple objects lacked a fancy name. So we gave them one, and it’s caught on very nicely.

Generally, a POJO is not bound to any restriction and any Java object can be called a POJO but there are some directions. A well-defined POJO should follow below directions.

  1. Each variable in a POJO should be declared as private.
  2. Default constructor should be overridden with public accessibility.
  3. Each variable should have its Setter-Getter method with public accessibility.
  4. Generally POJO should override equals(), hashCode() and toString() methods of Object (but it's not mandatory).
  5. Overriding compare() method of Comparable interface used for sorting (Preferable but not mandatory).

And according to Java Language Specification, a POJO should not have to

  1. Extend pre-specified classes
  2. Implement pre-specified interfaces
  3. Contain pre-specified annotations

However, developers and frameworks describe a POJO still requires the use prespecified annotations to implement features like persistence, declarative transaction management etc. So the idea is that if the object was a POJO before any annotations were added would return to POJO status if the annotations are removed then it can still be considered a POJO.

>A JavaBean is a special kind of POJO that is Serializable, has a no-argument constructor, and allows access to properties using getter and setter methods that follow a simple naming convention.

Read more on Plain Old Java Object (POJO) Explained.

Solution 7 - Java

there are mainly three options are possible for mapping purpose

  1. serialize
  2. XML mapping
  3. POJO mapping.(Plain Old Java Objects)

While using the pojo classes,it is easy for a developer to map with the database. POJO classes are created for database and at the same time value-objects classes are created with getter and setter methods that will easily hold the content.

So,for the purpose of mapping in between java with database, value-objects and POJO classes are implemented.

Solution 8 - Java

import java.io.Serializable;

public class Course implements Serializable {

	protected int courseId;
	protected String courseName;
	protected String courseType;

	public Course() {
		courseName = new String();
		courseType = new String();
	}

	public Course(String courseName, String courseType) {
		this.courseName = courseName;
		this.courseType = courseType;
	}

	public Course(int courseId, String courseName, String courseType) {
		this.courseId = courseId;
		this.courseName = courseName;
		this.courseType = courseType;
	}

	public int getCourseId() {
		return courseId;
	}

	public void setCourseId(int courseId) {
		this.courseId = courseId;
	}

	public String getCourseName() {
		return courseName;
	}

	public void setCourseName(String courseName) {
		this.courseName = courseName;
	}

	public String getCourseType() {
		return courseType;
	}

	public void setCourseType(String courseType) {
		this.courseType = courseType;
	}

	@Override
	public int hashCode() {
		return courseId;
	}

	@Override
	public boolean equals(Object obj) {
		if (obj != null || obj instanceof Course) {
			Course c = (Course) obj;
			if (courseId == c.courseId && courseName.equals(c.courseName)
					&& courseType.equals(c.courseType))
				return true;
		}
		return false;
	}

	@Override
	public String toString() {
		return "Course[" + courseId + "," + courseName + "," + courseType + "]";
	}
}

Solution 9 - Java

public class UserInfo {
        String LoginId;
        String Password;
        String FirstName;
        String LastName;
        String Email;
        String Mobile;
        String Address;
        String DOB;

        public String getLoginId() {
            return LoginId;
        }

        public void setLoginId(String loginId) {
            LoginId = loginId;
        }

        public String getPassword() {
            return Password;
        }

        public void setPassword(String password) {
            Password = password;
        }

        public String getFirstName() {
            return FirstName;
        }

        public void setFirstName(String firstName) {
            FirstName = firstName;
        }

        public String getLastName() {
            return LastName;
        }

        public void setLastName(String lastName) {
            LastName = lastName;
        }

        public String getEmail() {
            return Email;
        }

        public void setEmail(String email) {
            Email = email;
        }

        public String getMobile() {
            return Mobile;
        }

        public void setMobile(String mobile) {
            Mobile = mobile;
        }

        public String getAddress() {
            return Address;
        }

        public void setAddress(String address) {
            Address = address;
        }

        public String getDOB() {
            return DOB;
        }

        public void setDOB(String DOB) {
            this.DOB = DOB;
        }
    }

Solution 10 - Java

  1. File-setting-plugins-Browse repositories
  2. Search RoboPOJOGenerator and install, Restart Android studio
  3. Open Project and right click on package select on Generate POJO from JSON
  4. Paste JSON in dialogbox and select option according your requirements
  5. Click on Generate button

Solution 11 - Java

If a class is not bogged down from a framework or a library, then an object created from that class is recognized as a POJO.

Let's see some examples:

class MyServlet extends HttpServlet{
	//....
}

The sole meaning of MyServlet class is given by the HttpServlet class. Therefore the objects created from the MyServlet are not POJOs.

class MyClass implements Serializable{
	//...
}

The Serializable interface does not give a meaning to the class MyClass. Therefore the objects created from the MyClass are POJOs.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser405398View Question on Stackoverflow
Solution 1 - JavaduffymoView Answer on Stackoverflow
Solution 2 - JavaMd Azaharuddin AliView Answer on Stackoverflow
Solution 3 - JavaBlair ConradView Answer on Stackoverflow
Solution 4 - JavaSudarshanView Answer on Stackoverflow
Solution 5 - JavaJon HannaView Answer on Stackoverflow
Solution 6 - JavaNaresh JoshiView Answer on Stackoverflow
Solution 7 - Javamohit sarsarView Answer on Stackoverflow
Solution 8 - JavaAbdullah SarfarazView Answer on Stackoverflow
Solution 9 - JavaGowtham SubramaniamView Answer on Stackoverflow
Solution 10 - Javauser13256550View Answer on Stackoverflow
Solution 11 - JavaRushain SovisView Answer on Stackoverflow