SpringData :下划线的那些破事

今天写一个查询语句的时候,报错如下

org.springframework.beans.factory.BeanCreationException: 
Error creating bean with name 'tag_ArticleRepository':
Invocation of init method failed; 
nested exception is java.lang.IllegalArgumentException: 
Failed to create query method 
public abstract java.util.List com.fdzang.mblog.repository.Tag_ArticleRepository.getByTag_oId(java.lang.String)! 
No property tag found for type Tag_Article!

查询Repository如下

package com.fdzang.mblog.repository;

import com.fdzang.mblog.pojo.Tag_Article;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

public interface Tag_ArticleRepository extends JpaRepository<Tag_Article,String> {
    List<Tag_Article> getByTag_oId(String tag_oId);
}

一开始想到的是肯定是下划线会出问题,因为JPA对于命名规范比较严格,于是使用@Query注解进行测试

 @Query("SELECT ta FROM tag_article ta WHERE ta.tag_oId = :tag_oId")
    List<Tag_Article> getByTag_oId(@Param("tag_oId") String tag_oId);

报错如下

tag_article is not mapped

后来经过一番挫折,终于找到错误在哪儿了

 @Query("SELECT ta FROM Tag_Article ta WHERE ta.tag_oId = :tag_oId")
    List<Tag_Article> getByTag_oId(@Param("tag_oId") String tag_oId);

在@Query注解中,应该是实体的名称,而非数据库的表名,区分大小写

这个应该是Hibernate的底层实现原因,怪自己对Hibernate不熟悉而造成的

 

最后,总结一下:

以上是尚硅谷佟刚老师的SpringData教程,大致意思是在SpringDate的简单查询中,下划线有着特定的意思

他的解析会优先于在类里对比属性

如本次的 getByTag_oId() 就会解析为Tag_Article.Tag.oId 而不是Tag_Article.Tag_oId

因为下划线的优先级比较高,因此会先解析下划线,而后在类里进行比较

 

遇到这种问题的时候我们就可以基于注解开发了,毕竟SpringData的简单查询虽然简单,但是因为死板,所以命名方面比较苛刻

 

当然,最好的就还是别用这该死的下划线了!哈哈

posted @ 2018-08-31 23:42  市井俗人  阅读(1045)  评论(0编辑  收藏  举报