繁体   English   中英

如何在Spring数据JPA中获取结果集中的列名

[英]How to get column names in result set in Spring data JPA

我有列出用户的简单程序。 我使用@NamedStoredProcedureQueries进行过程声明,并使用EntityManager.createNamedStoredProcedureQuery进行StoredProcedureQuery

它正确返回结果,但我需要列名,以便我知道哪个值对应哪个列。

我的代码是这样的

实体类

@Entity
@NamedStoredProcedureQueries({ @NamedStoredProcedureQuery(name = 
    "sGetUserList", procedureName = "sGetUserList", parameters = { 
    @StoredProcedureParameter(mode = ParameterMode.IN, name = "user_id", type = 
    Integer.class) }) 
})
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    private String name;

    private String email;

    //getters and setters
}

自定义存储库

public interface UserRepositoryCustom {
    List<?> testProc() ;
}

存储库

public interface UserRepository extends JpaRepository<User, Long>, 
UserRepositoryCustom{

}

存储库实现

public class UserRepositoryImpl implements UserRepositoryCustom{

    @PersistenceContext
    EntityManager em;

    public List<Object> testProc() {

        StoredProcedureQuery q = em.createNamedStoredProcedureQuery("sGetUserList");
        q.setParameter("user_id", 1);
        List<Object> res = q.getResultList();

        return res;
    }
}

我需要列名的结果。

在这里,我写了一个方法从你可以得到JSON 你可以得到列和值的键值对

@Transactional
@Component
public class CustomRepository<T> {

    @Autowired
    private EntityManager em;

    private ObjectMapper mapper = new ObjectMapper();

    public List<T> getResultOfQuery(String argQueryString,Class<T> valueType) {
        try {
            Query query = em.createNativeQuery(argQueryString);
            NativeQueryImpl nativeQuery = (NativeQueryImpl) query;
            nativeQuery.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE);
            List<Map<String,Object>> result = nativeQuery.getResultList();
            List<T> resultList = result.stream()
                    .map(o -> {
                        try {
                            return mapper.readValue(mapper.writeValueAsString(o),valueType);
                        } catch (Exception e) {
                            ApplicationLogger.logger.error(e.getMessage(),e);
                        }
                        return null;
                    }).collect(Collectors.toList());
            return resultList;
        } catch (Exception ex) {
            ApplicationLogger.logger.error(ex.getMessage(),ex);
            throw ex;
        }
    }
}

唯一的条件是您的查询和 pojo 属性名称应该相同

您可以在 Map 中获取列名称及其值。 Map<'column-name', value>

Query query = entityManager.createNativeQuery("{call <<Your procedure>>}");
NativeQueryImpl nativeQuery = (NativeQueryImpl) query;
nativeQuery.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE);
List<Map<String,Object>> result = nativeQuery.getResultList();

这在您希望使用列名作为 HTML 中的占位符的地方非常有用,其中 value 将在运行时替换它。

我不确定我是否理解你在这里想要做什么。 如果您想让所有用户都使用 Spring 数据,则不应实施 UserRepository。 Spring Data 为你做这件事。

事实上 JpaRepository 已经有你需要的方法。

List<User> findAll();

您可以调用它来获取所有用户的列表,而无需担心列名称。

只需将您的存储库注入您需要的位置并调用该方法即可获取所有用户:

@Autowire
UserRepository userRepository;

List<Users> allUsers = userRepository.findAll();

编辑:如果您有特殊原因想要使用存储过程,尽管有一种 Spring Data 方法可以在不自己实现 UserRepository 的情况下执行此操作。 您可以通过定义以下方法来做到这一点:

public interface UserRepository extends JpaRepository<User, Long>{
   @Procedure(name = "sGetUserList")
   List<User> sGetUserList(@Param("user_id") Integer userId);

}

同样,使用此方法解析列名应该没有任何问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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