Home > Net >  What is the best practice with my Entity-Class and its "logic" - split up or not? If so, h
What is the best practice with my Entity-Class and its "logic" - split up or not? If so, h

Time:11-27

I´ve started with learning Hibernate and need to ask something about best-practice related to Entity-Classes and possible method-logic. Following are my simple examples :)

@Entity
public class Service {
    @Id
    @GeneratedValue
    @Column(name = "service_id")
    private int serviceID;

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

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

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

    @Column(name = "port")
    private Integer port;

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

    /*
     * Origin of my question (simple logic for microservices)
     */

    private boolean pingURL() {
       ... do something with port etc ...
    }

    public void boot() {
       ... do something with port and pingURL() ...
    }

My question is - is it ok to put my "logic" here? Its a very simple example but i want to learn it right and in a clean way. Lets say there are 5 or 10 of those methods. Would it also be ok? Something bothers me and i think the right way would be to split the methods into separat class or something like that.

My Controller acts like this (simple example)

@PostMapping("/bootService")
public void bootService(@RequestBody Service service) {
    service.boot();
}

So if i would want to split up the "logic" from my entity, how would i a approche it the best way, so that i could still work with Service (service.boot()) in my controller?

Thanks for helping me :)

***EDIT:

With @Alien´s answer, which is what i thought, i approached it like this:

public class ServiceHandler {
    private Service service;
    
    public ServiceHandler(Service service) {
        this.service = service;
    }

    /*
     * Origin of my question (simple logic for microservices)
     */

    private boolean pingURL() {
       ... do something with port etc ...
    }

    public void boot() {
       ... do something with port and pingURL() ...
    }
}

And my Controller would look like this:

@PostMapping("/bootService")
public boolean bootService(@RequestBody Service service) {
    ServiceHandler serviceHandler = new ServiceHandler(service);
    serviceHandler.boot();
}

Is this better or what could i do better?

CodePudding user response:

The entity class should only contain fields and getter/setters, hashcode and equals methods.

Or some methods to manipulate the transient variable data if any.

Write your logic in some service class.

  • Related