【发布时间】:2014-06-20 19:03:33
【问题描述】:
我在 spring webmvc 项目中使用 spring-data-jpa。我在我的一个实体的存储库上使用query creation 时遇到问题。您可以在下面看到我的实体、我的存储库和异常。
我的实体:
@Entity
@Table(schema = "mainschema")
@XmlRootElement
public class Municipalperson implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(nullable = false)
private Integer id;
@Basic(optional = false)
@Column(name = "municipal_id", nullable = false)
private Integer municipal_id;
@Basic(optional = false)
@Column(nullable = false, length = 60)
private String firstname;
public Municipalperson(Integer id, Integer municipal_id, String firstname) {
this.id = id;
this.municipal_id = municipal_id;
this.firstname = firstname;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getMunicipal_id() {
return municipal_id;
}
public void setMunicipal_id(Integer municipal_id) {
this.municipal_id = municipal_id;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
}
我的仓库:
@Repository
public interface MunicipalpersonRepository extends JpaRepository<Municipalperson, Integer> {
List<Municipalperson> findByMunicipal_idOrderByLastnameDesc(int municipal_id);
}
还有一个例外,
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'municipalpersonRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property municipal found for type Municipalperson!
我尝试将 municipal_id 设置为 int,然后设置为 Integer,并且我的存储库中的参数 municipal_id 也是如此,但没有任何效果。另外,我将存储库重命名为findByMunicipalidOrderByLastnameDesc 和findByMunicipalIdOrderByLastnameDesc,但它也不起作用。
最后我将municipal_id重命名为municipalId(删除了下划线),还重命名了getter/setter和存储库(findByMunicipalIdOrderByLastnameDesc),问题已解决。
我的问题是为什么会这样?
【问题讨论】:
-
Spring Data JPA 严重依赖 Java 命名约定。您选择在字段和访问器名称中使用下划线来不尊重它们。这就是你被咬的原因。尊重 Java 命名约定,Spring Data JPA 会很高兴,你的代码也会更易读。并不是说可以根据需要命名该列,包括下划线。重要的是您的映射字段名称。
-
非常感谢您的评论。我不知道 java 命名约定。我还发现这个stackoverflow question 也对我有帮助。
标签: java jpa spring-data repository spring-data-jpa