有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

因此,java JPA直接获取一个映射,而不是对象列表

我正在做一个项目,在这个项目中,使用JPA和下面的代码,我能够从DB中检索出一个包含用户配置文件的对象列表。每个对象都是一个双字段对象(单词、频率)

public class JpaUserprofilesDao implements UserProfilesDao {

@PersistenceUnit
private EntityManagerFactory emf;
EntityManager em;

public EntityManager getEntityManager() {
    return emf.createEntityManager();
}

@Transactional
@Override

 public List<Object[]> getUserProfiles(Long userId){       

    em = getEntityManager();
    try {

        List<Object[]> up =em.createQuery("SELECT up.userprofilesPK.word,  up.userprofilesPK.frequency  from Userprofiles up WHERE up.userprofilesPK.userid= :userid").setParameter("userid", userId).getResultList();

        return up;

    } finally {
        em.close();
    }        
 }
}

在我的项目的另一个类中,我使用以下代码块将上述信息放入地图中,并能够对其进行操作

profileObject = peristanceservice.getUserProfiles(userId);
              for(Object[] s: profileObject ){                       
                   if(!tempList.contains(s[0].toString())){                          
                       bag.put( (String) s[0].toString(), Integer.parseInt(s[1].toString()) );
                       tempList.add(s[0].toString());                                                 
                   }        
                }

尽管我得到了结果,但处理持久性服务返回的对象列表并将其放入映射需要很长时间,这最终证明是无用的。 有没有办法直接从持久性服务获取地图

提前谢谢你


共 (1) 个答案

  1. # 1 楼答案

    这并不完全是你想要的,但你可以使用它

    你可以用番石榴把List变成Map

    使用Maps.uniqueIndex

      Returns an immutable map for which the Map.values() are the given elements in the given order, and each key is the product of invoking a supplied function on its corresponding value.
    

    例如:

    Map<String,String> mappedRoles = Maps.uniqueIndex(yourList, new Function<String,String>() {
      public String apply(String from) {
        // do stuff here
        return result;
      }});