Business Logic On Entity Class

I am looking state pattern. (https://springframework.guru/gang-of-four-design-patterns/state-pattern/)

But I doesn`t find how to implement in my spring project.

I need declare variable of state instance on entity class as my understanding is right about state pattern. Because my entity class has state and need different behavior for each state.

But I think, entity class need pure because it represent database object.

What is best practice of state pattern for entity class of JPA?



  • You are definitely right, entity class should not implement any buisness logic. FurtherMore, if your entities are autoGenerated by any ORM framework, you can get serious troubles as long as your custom code will be regenerated.

    Try to use composition along with the State Pattern. Pseudo code:

    // Entity class
    public class Person
        public long Id {get; set;}    
        public string FirstName {get; set;}
        public string LastName {get; set;} 
        public long Status {get; set;}
    public class PersonState : IPersonState
        private Person person;
        public PersonState(Person person, ...)
            this.person = person;
        // Your state methods 
        public void SetActiveState()
             // do something with person status
             person.Status = ...
        public void SetInactiveState()
             // do something with person
             person.Status = ...

    So, you'll keep entitites pure and have a good design...