[英]Spring-Data-Jpa Repository - Underscore on Entity Column Name
我在 spring webmvc 项目上使用 spring-data-jpa。 我在我的一个实体的存储库上使用查询创建时遇到问题。 您可以在下面看到我的实体、我的存储库和异常。
我的实体:
@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
)和问题就解决了。
我的问题是为什么会这样?
我通过将字段重命名为不带下划线的名称解决了这个错误。
@Column(name = "municipal_id", nullable = false)
private Integer municipalId; // <-- field was renamed
请将以下属性添加到application.properties文件中:
spring.jpa.hibernate.naming-strategy=org.hibernate.cfg.ImprovedNamingStrategy
我知道这个问题很久以前就有人回答了,但它可以在未来帮助其他人。
根据Docs ,下划线是 spring 用于分隔属性名称的特殊字符。 如果你真的想坚持使用蛇形大小写符号,你可以将 nativeQuery 设置为 true 并解决这个问题:
@Query(value = "SELECT * FROM municipalperson WHERE municipal_id=?1 ORDER BY last_name DESC", nativeQuery = true)
List<Municipalperson> findByMunicipal_idOrderByLastnameDesc(int municipal_id);
另一种对我有用的方法是使用@JsonProperty来区分 REST 请求/响应中使用的字段名称和用于数据库的字段名称。 例如:
@JsonProperty("municipalId")
private Integer municipal_id;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.