AndreaNobili
AndreaNobili

Reputation: 43057

Can I inject an instance of a model class annoted with @Entity into a controller using Spring?

I am pretty new in Spring and I have the following doubt. In a web application I have the following entity class that map a database table:

@Entity
@Table(name = "KM_PROJECT_INFO")
public class KM_ProjectInfo implements Serializable {

    @Id
    @GeneratedValue
    private Long idProjectInfo;

    @Column(name = "name")
    private String name;

    @Column(name = "technology")
    private String technology;

    @ManyToOne
    @JoinColumn(name = "idCountry")
    private KMCountry country;

    @Column(name = "power")
    private long power;

    @Column(name = "cod")
    private String cod;

    @ManyToOne
    @JoinColumn(name = "idProjectInfoStatus")
    private KM_ProjectInfoStatus status;

    @Column(name = "folderTech")
    private long folderTech;

    @Column(name = "folderProject")
    private long folderProject;

    // GETTER & SETTER
}

In a view there is a form where the user can insert the value of the fields of the previous entity class. When the user click the submit button of this form it is performed an action of a controller (in the specific case it is a Struts 2 action controller, but I think that this is not important).

In this action I have to retrieve the value inserted by the user into the form fields and use these values to set the matching fields of the previous entity class, then I have to persist it on the DB using Hibernate.

So my doubt is: the previous entity class is annoted using @Entity annotation. Can I simply inject it into my controller? Can I inject an instance of a class annoted with @Entity?

Tnx

Upvotes: 0

Views: 628

Answers (3)

Prabhat Choudhary
Prabhat Choudhary

Reputation: 189

You don't need to inject this as a spring bean into your controller.

  • Just create an instance of the Entity.
  • Set the entity fields as per the form parameters.
  • Persist the entity in the DB.

Upvotes: 0

Devram Kandhare
Devram Kandhare

Reputation: 781

You just have to create object using simple java object creation:

KM_ProjectInfo obj = new KM_ProjectInfo();

And then use setter method to set properties and do database operations. You don't need to use spring bean creation.

Upvotes: 0

Master Slave
Master Slave

Reputation: 28569

You can make this happen', won't happen automatically as @Entity does not mark a class to be a spring bean. You can make it a Spring bean, but than Spring framework would take over managing the life-cycle of an entity object which should be an exclusive role of the JPA framework. Making this work in a sensible way would be a horrible struggle.

Luckily for you, from what you described you don't need to do this, simply create an instance of your Entity, populate it with form params and pass on the object to your service or DAO.

Upvotes: 1

Related Questions