spring data jpa @query返回map的踩坑记录

最近用spring data jpa,网上看的一些教程,有的说是返回的Object[]数组,有的说是直接返回的对象,亲身验证了一下,发现主要看写法和返回结果。

用的版本是这样的:

dao代码如下:

public interface UserRepository extends JpaRepository {

	/**
	 * 查询某些具体列,用Object[]数组接收
	 * @param realName
	 * @return
	 */
	@Query(value = "select u.userId,u.userName,u.realName from User u where u.realName = :realName")
	public Object[] getUserByRealName2(@Param("realName") String realName);
	
	/**
	 * 查询整个实体对象所有信息,可以直接用实体对象接收
	 * @param realName
	 * @return
	 */
	@Query(value = "select u from User u where u.realName = :realName")
	public User getUserByRealName3(@Param("realName") String realName);
	
	/**
	 * 返回List信息
	 * @param realName
	 * @return
	 */
	@Query(value = "select new map(u as user) from User u where u.realName = :realName")
	public List> getUserByRealName(@Param("realName") String realName);
	
	/**
	 * 返回map对象
	 * @param realName
	 * @return
	 */
	@Query(value = "select new map(u.realName as userName,o.orgName as orgName) from User u, Org o where u.realName = :realName")
	public Map getUserByRealName1(@Param("realName") String realName);
}

 

测试的代码如下,完全没什么问题。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:conf/root-context.xml"})
public class UserDaoTest {
	
	@Autowired
	private UserRepository userRepository;

	@Test
	public void test() {
		
		Object[] u2 = userRepository.getUserByRealName2("admin");
		
		User u3 = userRepository.getUserByRealName3("admin");
		
		List> u = userRepository.getUserByRealName("test");
		String userName = ((User) u.get(0).get("user")).getRealName();
		System.out.println(userName);
		
		
		Map u1 = userRepository.getUserByRealName1("admin");
		String name = ((User) u1.get("userName")).getRealName();
		System.out.println(name);
		
		
		
		
		assert(userName.equals("admin"));
	}

}

 

 

你可能感兴趣的:(个人学习之路)