Spring-Data-Jpa存储库 – 实体列名称的下划线
我在spring webmvc项目中使用spring-data-jpa。 我在我的一个实体的存储库上使用查询创建时遇到了问题。 您可以在下面看到我的实体,我的存储库和exception。
我的实体,
@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 { List 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!
我试图将mynicipal_id设置为int,然后设置为Integer,并将我的存储库中的参数’municipal_id’设置为相同,但它们都没有用。 此外,我将存储库重命名为’findByMunicipalidOrderByLastnameDesc’和’findByMunicipalIdOrderByLastnameDesc’,但它既不起作用。
最后,我将municipal_id重命名为municipalId(删除了下划线),并重命名getter / setter和Repository(findByMunicipalIdOrderByLastnameDesc)并解决了问题 。
我的问题是为什么会这样?
下划线_
是Spring Data查询派生中的保留字符(有关详细信息,请参阅参考文档 ),以便可能允许手动属性路径描述。 所以你有两个选择:
- 坚持使用camel-case作为成员变量名称的Java命名约定,一切都将按预期工作。
- 通过使用额外的下划线来转义
_
,findByMunicipal__idOrderByLastnameDesc(…)
查询方法重命名为findByMunicipal__idOrderByLastnameDesc(…)
。
我推荐前者,因为你不会疏远Java开发人员:)。
我通过将字段重命名为没有下划线的名称来解决此错误。
@Column(name = "municipal_id", nullable = false) private Integer municipalId; // <-- field was renamed
请将以下属性添加到application.properties文件中:
spring.jpa.hibernate.naming-strategy=org.hibernate.cfg.ImprovedNamingStrategy