当前位置:  开发笔记 > 编程语言 > 正文

如何使用Spring和Hibernate在Primefaces中执行懒惰的dataTable?

如何解决《如何使用Spring和Hibernate在Primefaces中执行懒惰的dataTable?》经验,为你挑选了1个好方法。

我必须将我的dataTable转换为惰性dataTable。我该怎么做?这是我的示例代码:

IndexBean.java

@Name("indexBean")
public class IndexBean implements Serializable {

    private static final long serialVersionUID = 1L;

    @Inject
    UserService userService;
    private List userList;

    @Inject
    MessageService messageService;
    private List messageList;

    private Integer dataTableRendered;

    public void getAllUser() {
        setDataTableRendered(1);
        userList = new ArrayList();
        userList = userService.getAllUser();
        if (userList.size() > 0) {
            addMessageSuccess("Success", "Success");
        } else {
            addMessageError("Failure", "Failure!");
        }
    }

    public void getAllMessages() {
        setDataTableRendered(2);
        messageList = new ArrayList();
        messageList = messageService.getAllMessages();
        if (messageList.size() > 0) {
            addMessageSuccess("Success", "Success");
        } else {
            addMessageError("Failure", "Failure!");
        }
    }

    public void addMessageSuccess(String summary, String detail) {
        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, summary, detail);
        FacesContext.getCurrentInstance().addMessage(null, message);
    }

    public void addMessageError(String summary, String detail) {
        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, summary, detail);
        FacesContext.getCurrentInstance().addMessage(null, message);
    }

    public List getUserList() {
        return userList;
    }
    public void setUserList(List userList) {
        this.userList = userList;
    }
    public List getMessageList() {
        return messageList;
    }
    public void setMessageList(List messageList) {
        this.messageList = messageList;
    }
    public Integer getDataTableRendered() {
        return dataTableRendered;
    }
    public void setDataTableRendered(Integer dataTableRendered) {
        this.dataTableRendered = dataTableRendered;
    }
}

index.xhtml




    


    
    

    
        
    

    
    

        

        

        

    

    
    

        

            
            

                
                    
                
                
                    
                
                
                    
                
            

            
                    
                
                
                    
                
                
                    
                
                
                    
                
                
                    
                

            

        

    


UserService.java

public interface UserService {

    public List getAllUser();
}

UserServiceImpl.java

@Service("userService")
@Component
@Transactional
public class UserServiceImpl implements UserService {


    @Autowired
    private UserDAO userDAO;

    @Override
    public List getAllUser() {
        return userDAO.getAllUser();
    }

}

UserDAO.java

public interface UserDAO {

    public List getAllUser();

}

UserDAOImpl.java- 实际上此sql更复杂。

@Component
@Repository("userDAO")
public class UserDAOImpl extends HibernateDaoSupport implements UserDAO {


    @SuppressWarnings("unchecked")
    @Override
    public List getAllUser() {
        List userList = new ArrayList();
        String sql = "select * from SECRETDB.USER";


        try {
            Query query = getSession().createSQLQuery(sql).addScalar("userOID", StringType.INSTANCE)
                    .addScalar("userName", StringType.INSTANCE).addScalar("firstName", StringType.INSTANCE)
                    .setResultTransformer(Transformers.aliasToBean(User.class)).setCacheable(false)
                    .setCacheMode(CacheMode.IGNORE);

            userList = query.list();
            getSession().clear();
        } catch (HibernateException e) {
            getSession().clear();
            e.printStackTrace();
        }

        return userList;
    }

User.java

public class User {

    private String userOID;
    private String userName;
    private String firstName;

    public String getUserOID() {
        return userOID;
    }

    public void setUserOID(String userOID) {
        this.userOID = userOID;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

}

HibernateDaoSupport.java

public abstract class HibernateDaoSupport {

    @Autowired
    private SessionFactory sessionFactory;

    protected Session getSession() {
        return sessionFactory.getCurrentSession();
    }
}

Mahendran Ay.. 5

在index.xhtml中的数据表中,我看到了

  value="#{indexBean.userList }" paginator="true" rows="10"
            lazy="true" 

userList指向的位置

  private List userList; 

错了 它应该是

  private LazyUserDataModel userList

请阅读展示和userguide页167-168实施LazyDataModel。这里没有人会你实现它。下面是使用hibernate和JPA的通用lazydatamodel的示例。

  public class GenericLazyDataModel extends LazyDataModel {

@Transient
protected static Logger debugLogger = Logger.getLogger("DebugLogger");

protected EntityManager entityManager;
protected String hqlQuery;
private String countQuery;
protected List defaultSortFields;
protected List currentObjectList;
protected List parameterValues;
protected List parameterName;

protected List filterFieldValues;
protected List filterFieldName;


public GenericLazyDataModel(EntityManager entityManager, String hqlQuery,
        String countQuery, List sortFieldInfos,
        List parameterValues, List parameterName) {
    super();
    this.entityManager = entityManager;
    this.hqlQuery = hqlQuery;
    this.countQuery = countQuery;
    this.defaultSortFields = sortFieldInfos;
    this.parameterValues = parameterValues;
    this.parameterName = parameterName;
    this.setRowCount(calculateRecordCount());

}

@Override
public List load(int first, int pageSize, String sortField,
        SortOrder sortOrder, Map filters) {

    String sqlQuery = hqlQuery;
    int filterCount = 0;
    if(sortOrder==null){
        sortOrder=SortOrder.ASCENDING;
    }

    if (filterFieldValues != null && filterFieldName != null) {
        filterFieldValues.clear();
        filterFieldName.clear();
    }
    for (Iterator iterator = filters.keySet().iterator(); iterator
            .hasNext();) {
        String filterField = iterator.next();
        if (debugLogger.isInfoEnabled()) {
            debugLogger.info("Filter Field Name " + filterField);
        }

        // Check if the HQL Query already has a where clause
        if (sqlQuery.toLowerCase().indexOf("where") != -1) {
            sqlQuery = sqlQuery + " and  " + filterField
                    + " like :filterFieldValue" + filterCount;
        } else {
            sqlQuery = sqlQuery + " where  " + filterField
                    + " like :filterFieldValue" + filterCount;
        }

        if (filterFieldValues == null) {
            filterFieldValues = new ArrayList();
        }

        if (filterFieldName == null) {
            filterFieldName = new ArrayList();
        }

        filterFieldValues.add(((String)filters.get(filterField)).toUpperCase() + "%");
        filterFieldName.add("filterFieldValue" + filterCount);
        filterCount++;

    }


    //************************
    boolean isOrderFieldFound=Boolean.FALSE;
    if(sortField !=null && !sortField.isEmpty()){
        isOrderFieldFound=Boolean.TRUE;
        sqlQuery = sqlQuery + " order by  " + sortField+(sortOrder==SortOrder.ASCENDING?" ASC ":" DESC ");
    }
    if(isOrderFieldFound){

        if(defaultSortFields !=null && !defaultSortFields.isEmpty()){
            for(SortFieldInfoDTO fld:defaultSortFields){
                if(!sqlQuery.contains(fld.getAliasedFieldName()))   sqlQuery=sqlQuery+" , "+fld.getAliasedFieldName()+(fld.getSortOrder()==SortOrder.ASCENDING?" ASC ":" DESC ");
            }
        }

    }else{
        if(defaultSortFields !=null && !defaultSortFields.isEmpty()){
            int index=0;
            for(SortFieldInfoDTO fld:defaultSortFields){
                if(index==0){
                    if(!sqlQuery.contains(fld.getAliasedFieldName())) sqlQuery = sqlQuery + " order by  " + fld.getAliasedFieldName()+(fld.getSortOrder()==SortOrder.ASCENDING?" ASC ":" DESC ");
                    index++;
                }else{
                    if(!sqlQuery.contains(fld.getAliasedFieldName())) sqlQuery=sqlQuery+" , "+fld.getAliasedFieldName()+(fld.getSortOrder()==SortOrder.ASCENDING?" ASC ":" DESC ");
                }
            }
        }
    }

    //*********************************
    if (debugLogger.isInfoEnabled())debugLogger.info("sqlQuery:"+sqlQuery);
    Query query = entityManager.createQuery(sqlQuery);
    int parameterCount = 0;
    if (parameterValues != null) {
        for (Iterator iterator = parameterValues.iterator(); iterator
                .hasNext();) {
            Object type = iterator.next();
            query.setParameter(parameterName.get(parameterCount), type);
            parameterCount++;
        }
    }

    int parameterCount1 = 0;
    if (filterFieldValues != null && !filterFieldValues.equals("")) {
        for (Iterator iterator = filterFieldValues.iterator(); iterator
                .hasNext();) {
            Object type = iterator.next();
            query.setParameter(filterFieldName.get(parameterCount1), type);
            parameterCount1++;
        }
    }

    if (debugLogger.isInfoEnabled())debugLogger.info("first page value " + first);
    if (debugLogger.isInfoEnabled())debugLogger.info("pageSize page value " + pageSize);

    query.setFirstResult(first);
    query.setMaxResults(pageSize);
    currentObjectList = query.getResultList();
    return currentObjectList;
}

private int calculateRecordCount() {
    Query query = entityManager.createQuery(countQuery);
    int parameterCount = 0;       
    if (parameterValues != null) {
        for (Iterator iterator = parameterValues.iterator(); iterator
                .hasNext();) {
            Object type = iterator.next();
            query.setParameter(parameterName.get(parameterCount), type);
            parameterCount++;
        }
    }

    if (filterFieldValues != null) {
        for (Iterator iterator = filterFieldValues.iterator(); iterator
                .hasNext();) {
            Object type = iterator.next();
            query.setParameter(filterFieldName.get(parameterCount), type);
            parameterCount++;
        }
    }

    Long rowCount = (Long) query.getSingleResult();
    if (debugLogger.isInfoEnabled()) {
        debugLogger.info("rowCount Application Data Model" + rowCount);
    }
    return rowCount.intValue();

}

public List getCurrentObjectList() {
    return currentObjectList;
}


}

使用这个并自己学习,祝您好运。



1> Mahendran Ay..:

在index.xhtml中的数据表中,我看到了

  value="#{indexBean.userList }" paginator="true" rows="10"
            lazy="true" 

userList指向的位置

  private List userList; 

错了 它应该是

  private LazyUserDataModel userList

请阅读展示和userguide页167-168实施LazyDataModel。这里没有人会你实现它。下面是使用hibernate和JPA的通用lazydatamodel的示例。

  public class GenericLazyDataModel extends LazyDataModel {

@Transient
protected static Logger debugLogger = Logger.getLogger("DebugLogger");

protected EntityManager entityManager;
protected String hqlQuery;
private String countQuery;
protected List defaultSortFields;
protected List currentObjectList;
protected List parameterValues;
protected List parameterName;

protected List filterFieldValues;
protected List filterFieldName;


public GenericLazyDataModel(EntityManager entityManager, String hqlQuery,
        String countQuery, List sortFieldInfos,
        List parameterValues, List parameterName) {
    super();
    this.entityManager = entityManager;
    this.hqlQuery = hqlQuery;
    this.countQuery = countQuery;
    this.defaultSortFields = sortFieldInfos;
    this.parameterValues = parameterValues;
    this.parameterName = parameterName;
    this.setRowCount(calculateRecordCount());

}

@Override
public List load(int first, int pageSize, String sortField,
        SortOrder sortOrder, Map filters) {

    String sqlQuery = hqlQuery;
    int filterCount = 0;
    if(sortOrder==null){
        sortOrder=SortOrder.ASCENDING;
    }

    if (filterFieldValues != null && filterFieldName != null) {
        filterFieldValues.clear();
        filterFieldName.clear();
    }
    for (Iterator iterator = filters.keySet().iterator(); iterator
            .hasNext();) {
        String filterField = iterator.next();
        if (debugLogger.isInfoEnabled()) {
            debugLogger.info("Filter Field Name " + filterField);
        }

        // Check if the HQL Query already has a where clause
        if (sqlQuery.toLowerCase().indexOf("where") != -1) {
            sqlQuery = sqlQuery + " and  " + filterField
                    + " like :filterFieldValue" + filterCount;
        } else {
            sqlQuery = sqlQuery + " where  " + filterField
                    + " like :filterFieldValue" + filterCount;
        }

        if (filterFieldValues == null) {
            filterFieldValues = new ArrayList();
        }

        if (filterFieldName == null) {
            filterFieldName = new ArrayList();
        }

        filterFieldValues.add(((String)filters.get(filterField)).toUpperCase() + "%");
        filterFieldName.add("filterFieldValue" + filterCount);
        filterCount++;

    }


    //************************
    boolean isOrderFieldFound=Boolean.FALSE;
    if(sortField !=null && !sortField.isEmpty()){
        isOrderFieldFound=Boolean.TRUE;
        sqlQuery = sqlQuery + " order by  " + sortField+(sortOrder==SortOrder.ASCENDING?" ASC ":" DESC ");
    }
    if(isOrderFieldFound){

        if(defaultSortFields !=null && !defaultSortFields.isEmpty()){
            for(SortFieldInfoDTO fld:defaultSortFields){
                if(!sqlQuery.contains(fld.getAliasedFieldName()))   sqlQuery=sqlQuery+" , "+fld.getAliasedFieldName()+(fld.getSortOrder()==SortOrder.ASCENDING?" ASC ":" DESC ");
            }
        }

    }else{
        if(defaultSortFields !=null && !defaultSortFields.isEmpty()){
            int index=0;
            for(SortFieldInfoDTO fld:defaultSortFields){
                if(index==0){
                    if(!sqlQuery.contains(fld.getAliasedFieldName())) sqlQuery = sqlQuery + " order by  " + fld.getAliasedFieldName()+(fld.getSortOrder()==SortOrder.ASCENDING?" ASC ":" DESC ");
                    index++;
                }else{
                    if(!sqlQuery.contains(fld.getAliasedFieldName())) sqlQuery=sqlQuery+" , "+fld.getAliasedFieldName()+(fld.getSortOrder()==SortOrder.ASCENDING?" ASC ":" DESC ");
                }
            }
        }
    }

    //*********************************
    if (debugLogger.isInfoEnabled())debugLogger.info("sqlQuery:"+sqlQuery);
    Query query = entityManager.createQuery(sqlQuery);
    int parameterCount = 0;
    if (parameterValues != null) {
        for (Iterator iterator = parameterValues.iterator(); iterator
                .hasNext();) {
            Object type = iterator.next();
            query.setParameter(parameterName.get(parameterCount), type);
            parameterCount++;
        }
    }

    int parameterCount1 = 0;
    if (filterFieldValues != null && !filterFieldValues.equals("")) {
        for (Iterator iterator = filterFieldValues.iterator(); iterator
                .hasNext();) {
            Object type = iterator.next();
            query.setParameter(filterFieldName.get(parameterCount1), type);
            parameterCount1++;
        }
    }

    if (debugLogger.isInfoEnabled())debugLogger.info("first page value " + first);
    if (debugLogger.isInfoEnabled())debugLogger.info("pageSize page value " + pageSize);

    query.setFirstResult(first);
    query.setMaxResults(pageSize);
    currentObjectList = query.getResultList();
    return currentObjectList;
}

private int calculateRecordCount() {
    Query query = entityManager.createQuery(countQuery);
    int parameterCount = 0;       
    if (parameterValues != null) {
        for (Iterator iterator = parameterValues.iterator(); iterator
                .hasNext();) {
            Object type = iterator.next();
            query.setParameter(parameterName.get(parameterCount), type);
            parameterCount++;
        }
    }

    if (filterFieldValues != null) {
        for (Iterator iterator = filterFieldValues.iterator(); iterator
                .hasNext();) {
            Object type = iterator.next();
            query.setParameter(filterFieldName.get(parameterCount), type);
            parameterCount++;
        }
    }

    Long rowCount = (Long) query.getSingleResult();
    if (debugLogger.isInfoEnabled()) {
        debugLogger.info("rowCount Application Data Model" + rowCount);
    }
    return rowCount.intValue();

}

public List getCurrentObjectList() {
    return currentObjectList;
}


}

使用这个并自己学习,祝您好运。

推荐阅读
kikokikolove
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有