IT Share you

POJO를 만드는 방법은 무엇입니까?

shareyou 2020. 11. 14. 11:22
반응형

POJO를 만드는 방법은 무엇입니까?


최근에 "POJO"(Plain Old Java Objects)에 대해 듣기 시작했습니다. 나는 그것을 봤지만 여전히 개념을 잘 이해하지 못한다. 누구든지 POJO에 대한 명확한 설명을 줄 수 있습니까?

변수 "id, name, address, salary"가있는 "Person"클래스를 고려하십시오.이 시나리오에 대한 POJO를 어떻게 생성합니까? 아래 코드는 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;
    }
}

POJO는 제한이 제거 된 평범하고 오래된 Java Bean입니다. Java Bean은 다음 요구 사항을 충족해야합니다.

  1. 인수없는 기본 생성자
  2. foo라는 변경 가능한 속성에 대해 getFoo (또는 부울의 경우 isFoo) 및 setFoo 메소드의 Bean 규칙을 따르십시오. foo가 불변이면 setFoo를 그대로 두십시오.
  3. java.io.Serializable을 구현해야합니다.

POJO는 이들 중 어떤 것도 요구하지 않습니다. 이름에서 알 수 있듯이 JDK에서 컴파일되는 객체는 Plain Old Java Object로 간주 될 수 있습니다. 앱 서버, 기본 클래스, 인터페이스가 필요하지 않습니다.

약어 POJO는 EJB 2.0에 대한 반응으로, 단순한 작업을 수행하기 위해 여러 인터페이스, 확장 된 기본 클래스 및 많은 메소드가 필요했습니다. 로드 존슨과 마틴 파울러와 같은 일부 사람들은 복잡성에 반발하고 EJB를 작성하지 않고도 엔터프라이즈 규모 솔루션을 구현할 수있는 방법을 모색했습니다.

Martin Fowler는 새로운 약어를 만들었습니다.

Rod Johnson은 "J2EE Without EJB"를 썼고, Spring을 썼고, EJB에 충분히 영향을 주었기 때문에 버전 3.1은 Spring과 Hibernate와 매우 비슷해 보였고, VMWare로부터 달콤한 IPO를 얻었습니다.

다음은 머리를 감쌀 수있는 예입니다.

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는 Java 언어 사양에 의해 강제되는 제한 외에는 제한되지 않는 Java 개체입니다.

POJO의 속성

  1. 모든 속성은 공용 setter 및 getter 메서드 여야합니다.
  2. 모든 인스턴스 변수는 비공개 여야합니다.
  3. 미리 지정된 클래스를 확장하면 안됩니다.
  4. 미리 지정된 인터페이스를 구현해서는 안됩니다.
  5. 미리 지정된 주석을 포함해서는 안됩니다.
  6. 인수 생성자가 없을 수 있습니다.

POJO의 예

public class POJO {

    private String value;

    public String getValue() {
         return value;
    }

    public void setValue(String value) {
        this.value = value;
    }
}

POJO는 Plain Old Java Object 입니다.

내가 링크 한 wikipedia 기사에서 :

컴퓨팅 소프트웨어에서 POJO는 Plain Old Java Object의 약자입니다. 이 이름은 주어진 객체가 특수 객체가 아니라 특히 Enterprise JavaBean 이 아닌 일반 Java 객체임을 강조하는 데 사용됩니다.

수업이 이미 POJO 인 것 같습니다.


POJO 클래스는 값을 설정하고 가져 오는 데 사용되는 빈 역할을합니다.

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

특정 프레임 워크, ORM 또는 특수한 종류의 클래스가 필요한 기타 시스템과 함께 작동하도록 특별히 설계된 클래스를 만들기 위해 아무것도하지 않는 경우에는 Plain Old Java Object 또는 POJO가 있습니다.

아이러니하게도이 용어를 만든 이유 중 하나는 사람들이 합리적 일 때 피하고 있었고 어떤 사람들은 이것이 멋진 이름이 없기 때문이라고 결론지었습니다. 당신의 질문은 접근 방식이 효과가 있음을 보여주기 때문에 아이러니합니다.

이전 POD "Plain Old Data"를 비교하여 C 구조체가 수행 할 수없는 작업을 수행하지 않는 C ++ 클래스를 의미합니다 (소멸자 또는 사소한 생성자가 아닌 비가 상 멤버는이를 중지하지 않습니다. POD로 간주 됨), .NET의 최신 (그리고보다 직접적으로 비교 가능한) POCO "Plain Old CLR Object".


매핑 목적으로 주로 세 가지 옵션이 가능합니다.

  1. 직렬화
  2. XML 매핑
  3. POJO 매핑 (Plain Old Java Objects)

pojo 클래스를 사용하는 동안 개발자가 데이터베이스와 쉽게 매핑 할 수 있습니다. POJO 클래스는 데이터베이스 용으로 생성되고 동시에 콘텐츠를 쉽게 보관할 수있는 getter 및 setter 메서드를 사용하여 value-objects 클래스가 생성됩니다.

따라서 Java와 데이터베이스 간의 매핑을 위해 value-objects 및 POJO 클래스가 구현됩니다.


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

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.


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

참고URL : https://stackoverflow.com/questions/3527264/how-to-create-a-pojo

반응형