简体   繁体   中英

how to let entity read db configuration

Consider the problem of entities that need to read some database configuration in order set some values : for example :

@entity
public class person{
int age,
String ageCategory;
}

ageCategory will be fetched from the database when age is set. my question what is the best EJB architecture to use in order to read AgeCategoryConfiguration from the databse. currently i am using jndi to inject the AgeCategoryFacade which provide a method to get AgeCategory from age, this method is called in the age setter .

is there a better approach.

Maybe you want to look at jpa Events .

You stated that ageCategory will be fetched from the database when age is set this and i think this statement fits @PostLoad annotation.

If you want to know more read this nice article . And usually you should not need jndi paths while injecting ejbs.

Edit I would keep things as simple as possible.

So you should have some bean which is used in JSF with method for updating person:

@Named
@SessionScoped
public class PersonController {

    @Inject
    private PersonService personService;

    private Person selectedPerson;

    /**
     * Method for updating.
     */
    public void updatePerson(ActionEvent actionEvent){
        Person updatedPerson = personService.update(selectedUser);
        // pass updatedPerson to presentation layer..
    }
}

Next you should have PersonService which takes care of Person's CRUD operations :

@Stateless
@LocalBean
public class PersonService {

    @PersistenceContext
    private EntityManager em;

    @Inject
    private AgeCategoryFacade ageCategoryFacade;

    public Person updatePerson(Person person) {
         // use ageCategoryFacade somehow to set ageCategory for example:
         String ageCategory = ageCategoryFacade.getAgeCategory(person.getAge());
         person.setAgeCategory(ageCategory);
         return (Person) em.merge(person);
    }
}

Note that you can use ageCategoryFacade also in other methods like createPerson, findPerson.

Solution with JPA events involves PostLoad(or PrePersist) method in entity Bean:

@Entity
public class Person {
    int age;
    String ageCategory;

    /**
     * Simple setting of ageCategory.
     */
    @PostLoad
    public void postLoadPerson {
        if(age < 10) {
            setAgeCategory("A");
        } else if (age < 30) {
            setAgeCategory("B");
        } else {
            setAgeCategory("C");
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM