How to create a POJO? - java

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;
}
}

A POJO is just a plain, old Java Bean with the restrictions removed. Java Beans must meet the following requirements:
Default no-arg constructor
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.
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; }
}

POJO:- POJO is a Java object not bound by any restriction other than those forced by the Java Language Specification.
Properties of POJO
All properties must be public setter and getter methods
All instance variables should be private
Should not Extend prespecified classes.
Should not Implement prespecified interfaces.
Should not contain prespecified annotations.
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;
}
}

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.

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;
}
}

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.

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.
Each variable in a POJO should be declared as private.
Default constructor should be overridden with public accessibility.
Each variable should have its Setter-Getter method with public accessibility.
Generally POJO should override equals(), hashCode() and toString() methods of Object (but it's not mandatory).
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
Extend pre-specified classes
Implement pre-specified interfaces
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.

there are mainly three options are possible for mapping purpose
serialize
XML mapping
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.

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 + "]";
}
}

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;
}
}

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

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.

Related

How do you create Collections in Brightspot CMS using Java classes with the Dari framework?

import com.psddev.cms.db.Content;
import com.psddev.dari.db.Recordable;
public class MattContent extends Content {
private String tt;
private String uu;
public String getUu() {
return uu;
}
public MattContent setUu(String uu) {
this.uu = uu;
return this;
}
public String getTt() {
return tt;
}
public MattContent setTt(String tt) {
this.tt = tt;
return this;
}
#Recordable.DisplayName("Headline")
private String title;
#Recordable.DisplayName("Fields")
private String fields;
#Recordable.Regex(value=".+\\#.+\\..+", validationMessage="Use email format 'myemail#address.com'")
private String email;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
The code above renders individual fields in the UI from a Java class using the Dari framework in Brightspot CMS. I would like to do more than individual fields, but Collections as well.
I can see how to set up a Collection for users in the docs:
https://docs.brightspot.com/4.0/en/plugins-guide/collections/creating-collections.html
However, I cannot find the annotation in Dari to set this up for devs:
https://docs.brightspot.com/4.2/en/dari-guide/data-modeling/data-modeling-annotations.html
I'd really appreciate any help in pointing me to the right section of the documentation. This may be a vocabulary issue -- I may not be typing in the right words to get this information.
*"Cluster" isn't yielding the results I'm looking for either.
Thanks for your time and help.
Solution: There is no annotation needed for a collection. One can write a simple set or list:
private Set<Internal> internalSet;
private List<Internal> internalList;
The solution is so simple, I overlooked the obvious: annotations are extras in Dari, not essential for rendering content to Brightspot CMS' UI.

How to use autobean for converting json to java class in GWT

I have a class Person in gwt and I have sent an instance of Person with servlet converted using Gson from server to client. But in the client side seems I can't use Gson. From what I read in forums it seems that the best way is using AutoBeans to convert Json to object Person again.
However in AutoBeans I can only use an interface. I will appreciate if anyone can help me write it.
A json example I get from server and want to convert to Person class again:
{"name":"aaa","family":"fff","username":"uuu","age":20,"phones":[{"id":0,"phoneNumber":"0911111"}],"relatives":[null]}
public class Person implements Serializable {
private String name;
private String family;
private String username;
private int age;
private List<Phone> phones;
private List<Person> relatives;
public Person() {
}
public Person(String name, String family, String username, int age, List<Phone> phones, List<Person> relatives) {
this.name = name;
this.family = family;
this.username = username;
this.age = age;
this.phones = phones;
this.relatives = new ArrayList<Person>();
this.relatives = relatives;
}
public void addPhone(Phone p) {
phones.add(p);
}
public String getName() {
return this.name;
}
public String getFamily() {
return this.family;
}
public int getAge() {
return this.age;
}
public String getUsername() {
return this.username;
}
public List<Phone> getNumbers() {
return this.phones;
}
public List<Person> getRelatives() {
return this.relatives;
}
public String getAllNumbers() {
return Phone.convertPhonesToText(phones);
}
public static Person findPerson(List<Person> personList, String username) {
// .....
}
public static List<Person> convertTextToPersons(List<Person> personList, String personsText) {
// .....
}
public String convertPersonsToText() {
// ....
}
}
Yep, as commented by Tobika the other answer indicates that AutoBeans requires an Interface. AutoBeans feets better if you use it on both sides, client and server side and you define all your models as interfaces.
If you want to use your class models, you can use GWT Jackson which is pretty similar to AutoBeans but it uses your models, binding the json to your model (like other server side libraries; jackson, gson, etc):
https://github.com/nmorel/gwt-jackson
public static interface PersonMapper extends ObjectMapper<Person> {}
#Override public void onModuleLoad() {
PersonMapper mapper = GWT.create(PersonMapper.class);
String json = mapper.write(new Person("John", "Doe"));
GWT.log( json ); // > {"firstName":"John","lastName":"Doe"}
Person person = mapper.read(json);
GWT.log(person.getFirstName() + " " + person.getLastName());
}
Alternatively, you can use just plain GWT with JsInterop. This has many limitations but even with this limitation, it is a pretty good option. This is my favorite option if you can avoid inheritance in your DTOs. But this has the big advantage of being super lightweight (actually zero overhead mapping overhead and zero code overhead as it uses native parsing and no copies, accesing directly to the parsed json object). Limitations: cannot use inheritance, "broken type system" (all X instanceof SomeDtoType returns always true as all DTOs are of type Object wich makes sense because we are actually using the parsed JSON), cannot use collections only native arrays (but thanks to java8 Stream this should not be a problem, whatever you want to do with start with Stream.of(arr)), and only Double and Boolean boxed types supported (not supported any fancy type like Date or BigInteger, not supported long/Long...).
#JsType(isNative=true, package=GLOBAL, name="Object") final class Person {
// you can use getter/setter but as this class is final DTO adds no value
public String firstName; public String lastName; public Phome[] numbers;
// you can add some helper methods, don't forget to skip serialization!
public final #JsOverlay #JsonIgnore List<Phone> getNumberList() {
return Stream.of(numbers).collect(Collectors.toList());
}
}
#JsType(isNative=true, package=GLOBAL, name="Object) final class Phone {
public String number;
}
#JsMethod(namespace = "JSON") public static native <T> T parse(String text);
#Override public void onModuleLoad() {
Person person = parse("{\"firstName\":\"John\",\"lastName\":\"Doe\"}");
GWT.log(person.firstName + " " + person.lastName);
}
These simple and limited DTOs are more a DTO scheme than a type. But has a big advantage, this DTOs works out of the box with most of the server side parsers. Jackson and GSON will encode and parse without any configuration.

How to represent java object as return type of service in .thrift file

I'm developing a service using apache thrift. I have a service named getUser which returns User object. I couldn't find any way to define user-defined data type as a return type for my service defined in .thrift file.
user.thrift file looks like:
service UserService
{
User getUser(1:i32 userId),
}
When I am compiling the user.thrift to generate java source code, I am getting "Type "User" has not been defined" error. Can anyone please help me, how to represent this user-defined java object as a data type in thrift.
The getUser method code in service implementation class:
#Override
public User getUser(int user id) throws TException {
// here is the code that fetch the user object from database
return user;
}
This is my User class, whose object is being returned by service getUser:
public class User {
private int userId;
private String name;
private String city;
private String country;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
The relevant IDL could look like this:
struct User {
1 : i32 userId
2 : string name
3 : string city
4 : string country
}
So that's pretty straightforward. With that, you have two options:
use the Thrift-generated class as the data object, replacing your existing class
write some code that converts the data back and forth.
Both options have their pros and cons. With the first approach, you will lose the getter-only for the Id, because the field must be read/writable. But you don't have to convert any data.
The second approach leaves you with the getter/setter structure you have right now, with some minor modifications (the factory pattern could be worth a look). You pay that with the burden of additional data conversion from Thrift into your class and back.
It depends on the exact requirements, which option is the better one for your case.

Convert Userdefined Object to a String Object

I have a user defined class, say
import java.util.Calendar;
public class Employee{
private String name;
private int age;
private Calendar dob;
private Address address;
private boolean married;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Calendar getDob() {
return dob;
}
public void setDob(Calendar dob) {
this.dob = dob;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public boolean isMarried() {
return married;
}
public void setMarried(boolean married) {
this.married = married;
}
}
class Address{
private int doorNo;
private String streetName;
private String city;
public int getDoorNo() {
return doorNo;
}
public void setDoorNo(int doorNo) {
this.doorNo = doorNo;
}
public String getStreetName() {
return streetName;
}
public void setStreetName(String streetName) {
this.streetName = streetName;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
I am creating an object of Employee and populating it with setters. I have to represent the above object to string (encrypted or human-readable) and parse back to get similar object. Actually, I want to save the string equivalent of java object in a file and to read back them to get a java object. I know we have object writing, but they are sensitive to edit. I would prefer if a java object can be converted to String of human readable form. Thanks.
To keep your flattened object human readable and hand editable consider encoding your object into a JSON string using one of the popular JSON libraries. Same JSON library will also provide you APIs to decode a JSON string into your object.
One of the popular JSON library is Gson. Here's an use example: Converting JSON to Java
You should override toString() to convert instances of your class to string. As for recreating instances based on their string representation you can define a static factory method for this.
public class Employee {
...
#Override
public String toString() {
...
}
public static Employee fromString(String str) {
...
}
}
You use these methods like this:
To obtain string representation of an instance to string:
Employee john = ...
String johnString = john.toString();
Note that your toString() method will also be called implicitly whenever there is a need to obtain string representation of one of the instances.
To recreate an instance from string:
Employee john = Employee.fromString(johnString);
If you often need to store instances of the class in a file and read them back, you may also consider serialization. See documentation for Serializable interface as well as ObjectInputStream and ObjectOutputStream. You may also want to familiarize yourself with caveats surrounding serialization by reading the last chapter ("Serialization") in Effective Java, second edition. Most importantly be aware that the serialized form of your class becomes part of your public API.
You might be looking for the toString method:
Returns a string representation of the object. In general, the
toString method returns a string that "textually represents" this
object. The result should be a concise but informative representation
that is easy for a person to read. It is recommended that all
subclasses override this method.
In your case you would be doing something of the sort (to be added in each of your classes):
#Override
public String toString()
{
return "Name = " + name + ...
}
The string can be of any format you wish. To save the object, all that you need to do is to write the text that the toString method returns to a file.
To read them back, however, you will have to implement your own logic. On the other hand, what you can do, is to use something such as XStream (instructions here) which will automatically convert your object to XML.
XML is human readable so that your users can modify whatever they need. Once this is done, you can re-use XStream to read back your object.
Try this
Employee em = new Employee;
//Your code
str obj= JavaScriptSerializer.Serialize();
// whenever you want to get object again
Employee emp = (Employee)JavaScriptSerializer.Deserialize();

JAXB and constructors

I'm starting learning JAXB, so my question can be very silly. Now I have classes and want generate XML Schema. Going after this instruction I get exception
IllegalAnnotationExceptions ... does not have a no-arg default
constructor.
Yeah. My classes haven't default no-arg constructors. It's too easy. I have classes with package visible constructors / final methods and off course with arguments. What shall I do - create some specific momemto/builder classes or specify my constructors to JAXB (in what way?) ? Thanks.
JAXB can support this case using an XML Adapter. Consider you have the following object with no zero-arg constructor:
package blog.immutable;
public class Customer {
private final String name;
private final Address address;
public Customer(String name, Address address) {
this.name = name;
this.address = address;
}
public String getName() {
return name;
}
public Address getAddress() {
return address;
}
}
You simply need to create a mappable version of this class:
package blog.immutable.adpater;
import javax.xml.bind.annotation.XmlAttribute;
import blog.immutable.Address;
public class AdaptedCustomer {
private String name;
private Address address;
#XmlAttribute
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
And an XML Adapter to convert between them:
package blog.immutable.adpater;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import blog.immutable.Customer;
public class CustomerAdapter extends XmlAdapter<AdaptedCustomer, Customer> {
#Override
public Customer unmarshal(AdaptedCustomer adaptedCustomer) throws Exception {
return new Customer(adaptedCustomer.getName(), adaptedCustomer.getAddress());
}
#Override
public AdaptedCustomer marshal(Customer customer) throws Exception {
AdaptedCustomer adaptedCustomer = new AdaptedCustomer();
adaptedCustomer.setName(customer.getName());
adaptedCustomer.setAddress(customer.getAddress());
return adaptedCustomer;
}
}
Then for properties that refer to the Customer class, simply use the #XmlJavaTypeAdapter annotation:
package blog.immutable;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import blog.immutable.adpater.CustomerAdapter;
#XmlRootElement(name="purchase-order")
public class PurchaseOrder {
private Customer customer;
#XmlJavaTypeAdapter(CustomerAdapter.class)
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
}
For a more detailed example see:
http://bdoughan.blogspot.com/2010/12/jaxb-and-immutable-objects.html
You can use the annotation #XmlType and use factoryMethod / factoryClass attributes in various combinations such as:
#XmlType(factoryMethod="newInstance")
#XmlRootElement
public class PurchaseOrder {
#XmlElement
private final String address;
#XmlElement
private final Customer customer;
public PurchaseOrder(String address, Customer customer){
this.address = address;
this.customer = customer;
}
private PurchaseOrder(){
this.address = null;
this.customer = null;
}
/** Creates a new instance, will only be used by Jaxb. */
private static PurchaseOrder newInstance() {
return new PurchaseOrder();
}
public String getAddress() {
return address;
}
public Customer getCustomer() {
return customer;
}
}
Surprisingly this works and you get an initialized instance when unmarshalling. You should make note not to call the newInstance method anywhere on your code as it will return an invalid instance.
You should have a default constructor for JAXB to be able to instantiate your classes. Maybe there is a workaround I don't know though.
JAXB is especially fitted for bean-like classes, permitting to configure objects by calling setters on them.
JAXB re-creates beans from XML in a simple fashion : it creates a new instance of the bean, and then do all the setXXX needed to set the attributes. So, if your bean doesn't have a no-args constructor, JAXB can't create it. As said in other answers, JAXB works better for simple "container" beans, for which no-args constructor isn't really a problem. If you're trying to create beans that need specific initialization, you'll need to do it in the setXXX methods.

Categories