0

I have the next situation. I have POJO class:

    @Entity
    @Table(name="project")
    public class Project {

        public Donation donation;

        public Project() {}
        public Project(int param1, int param2 ...) {
            ...//other field initialisied
            donation = new Donation(param1, param2);
        }

        //methods

        @OneToOne
        @JoinColumn(name = "donation_project_id")
        public Donation getDonation() {
            return donation;
        }
    }

        public void setDonation(Donation donation) {
            this.donation = donation;
        }
    }

Donation class:

@Entity
@Table(name="donation")
public class Donation {

        public Donation() {}

        public DonationLogic(int param1, int param2) {
            //initialisation
        }
        //other methods
}

Project table/class relays some parameters to another table/class Donation. Two classes are Entities. And I use Spring+Hibernate. My question is if I correctly initiate class Donation which is created in constructor of Project class? I think using new operator inside Spring smells bad. Maybe there is another way to do this task? - create class/table that is filled from another table/class. Maybe separate parameters for two classes and not use one constructor to initiate to classes? But use setters of Donation class? However if I have many parameters, many setters I will need to use((( Hmm((

ovod
  • 1,118
  • 4
  • 18
  • 33
  • hibernate requires a no-argument constructor for all persistent classes – leeor Sep 25 '15 at 20:59
  • Sorry. My mistake. I forgot defualt constructor. But you didnt understand my question. Edited question. – ovod Sep 25 '15 at 21:09

1 Answers1

0

I think using new operator inside Spring smells bad.

Not really. But, anyway, you shouldn't use new in @Entity class and whole model layer. Instead of that you should move new to service layer, because now it looks like business logic is in your entity class.

Returning to your question: you should better reconsider your app architecture. As I said, new operator shouldn't be used inside model layer and @Entity classes. You are creating new bean, so it looks like some logic action. So move this action to @Service class and use @Repository as DAO to access basic operations on persistence objects. Your DAO will support and handle @OneToOne annotation without writing new in your entity beans.

Helpful link: Effective pattern for data access with JPA

Everv0id
  • 1,862
  • 3
  • 25
  • 47