Rajat Gupta
Rajat Gupta

Reputation: 26617

How should I go about reading the data from DB inside the managed beans?

I need to read/write data of a post(in a forum website). For reading the data of post, I need to read title of post, content Of Post & post owner. My question is how do I go about fetching the data for these fields from DB. I am making a single function called fillNow() which shall fill in the Data read from DB. Thus making the data available for all getProperty() methods of post inside the bean. Thus all the data from DB is read at once. Is there a better way ?

Upvotes: 0

Views: 87

Answers (1)

Dejell
Dejell

Reputation: 14337

The best approach is to create a method annotated with @PostConstruct inside the bean: @PostConstruct in being invoked only once when the bean is being created.

@ManagedBean
@ViewScope
public class PostBean{

  PostData post;

  @PostContruct
  public void initBean(){
    post = dbManager.getPostData(id);

  }
  public PostData getPost(){
  return post;
  }
  public void setPost(PostData post){
  this.post = post;
  }
}

PostData - should be your screen elements. add getters and setters to the method dbManager - will be your manager/service to bring the data from db

Upvotes: 2

Related Questions