Search code examples
jakarta-eejpaejbmanaged-beanjta

Java EE - Entity management in GUI


I'm using JPA with JTA in a Java EE enterprise application including an ejb and a web module that includes the managed beans related to the web pages.

The managed beans should be able to retrieve entities from the database passing through methods offered by my ejbs.

I have a User entity representing the data of the users registered in the system, and I want to allow the user to modify his email, his password and some other settings.

For instance let's consider this entity (abstracted from all the factors that doesn't have influence here):

@Entity
public class User {
..........
    private string email;
    *getter and setter for email*
    private string city;
    *getter and setter for city*
..........
}

In my web module I have xhtml files referencing Managed beans via Expression Language.

for instance I may have in Index.xhtml

<someEditableTag>#{myBean.user.email}</someEditableTag>
<someEditableTag>#{myBean.user.city}</someEditableTag>
<someButton>#{myBean.user.confirm()}</someButton>

In my bean then:

@Managed
@RequestScoped
public class myBean {
..........
   private user;
   public getUser() {
     if(user == null)
       user = someEJB.getLoggedUser(); // Retrieve from DB the user entity associated to logged user
     return user;
   }
   public void confirm() {
   // Call some ejb method to update the settings of the user in the database with the new data on the page
   }
..........
} 

My issue is that if the editable fields refer to my entity in the persistence context, shouldn't this already in some manner trigger an update when I edit the data on the page? Not exactly while I'm writing the data, but the edited data reference my entity via Expression Language in the xhtml.

In short, I'm afraid that the managed bean could modify the entity in the database just by accessing the setters of the entity I return from my ejb if the changes in the managed entity are committed automatically and not by using my confirm function that calls some ejb's method.

There's a lot I don't know about these tools so I'd like to have your opinion on this doubt I just mentioned.

I thought about some solutions, like for instance detaching the entities in the ejbs before passing them to the managed beans but that doesn't seem like a good solution. I'd like to know what is the standard design pattern for this kind of issues. Any example of solution would work fine.

Any help is greatly appreciated, Thank you in advance


Solution

  • Until you wont execute merge or insert metohod from EntityManager on your entity, nothing should happen in DB. You can always refresh your entity with EntityManager. However, if you are affraid to use entity in your web tire, you can always use DTO pattern.