如何在我们的自定义存储库中使用findByxxx

时间:2014-10-23 07:57:16

标签: rest spring-data

我想使用findByHostObjectId来查询MyEnity,但它说“找不到类型MyEntity 的属性hostObjectId”

我有我的Rest Controller和 @autowired MyRepository,我想使用MyRepository.findByHostObjectId(hostObjectId)通过请求参数(hostObjectId)获取MyEntity。

存储库

public interface MyRepository extends PagingAndSortingRepository<MyEntity, MyEntityId> {
//success 
MyEntity findById(@Param("id") MyEntityId id);

//fail
MyEntity findByHostObjectId(@Param("hostObjectId") Integer hostObjectId);}

myEntity所

public class MyEntity implements java.io.Serializable {

private MyEntityId id;

public MyEntity() {
}

public MyEntity(MyEntityId id) {
    this.id = id;
}

@EmbeddedId
public MyEntityId getId() {
    return this.id;
}

public void setId(MyEntityId id) {
    this.id = id;
}}

MyEntityId

@Embeddable
public class MyEntityId implements java.io.Serializable {
private static final long serialVersionUID = 1L;

private int objectId;
private Integer hostObjectId;
private String hostName;

public MyEntityId() {
}

public MyEntityId(int objectId, Integer hostObjectId, String hostName) {
    this.objectId = objectId;
    this.hostObjectId = hostObjectId;
    this.hostName = hostName;
}

public int getObjectId() {
    return this.objectId;
}

public void setObjectId(int objectId) {
    this.objectId = objectId;
}

public Integer getHostObjectId() {
    return this.hostObjectId;
}

public void setHostObjectId(Integer hostObjectId) {
    this.hostObjectId = hostObjectId;
}

public String getHostName() {
    return this.hostName;
}

public void setHostName(String hostName) {
    this.hostName = hostName;
}}

MyEntiry.hbm.xml

<hibernate-mapping>
    <class name="sud.MyEntity" table="sud_view_myentity">
    <composite-id name="id" class="sud.MyEntityId">
        <key-property name="objectId" type="int">
             <column name="OBJECT_ID" />
        </key-property>
        <key-property name="hostObjectId" type="java.lang.Integer">
             <column name="HOST_OBJECT_ID" />
        </key-property>
        <key-property name="hostName" type="string">
             <column name="HOST_NAME" length="64" />
        </key-property>
   </composite-id>
   </class>
</hibernate-mapping>

2 个答案:

答案 0 :(得分:0)

您是否尝试过将属性表达式用于嵌套属性,例如findByMyEntityId_HostObjectId?我不确定这是否可行,因为embeddable classes id是特殊情况。

查看链接中的示例

http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.query-methods.query-property-expressions

答案 1 :(得分:0)

非常感谢

它有效!!!

MyEntity findById_HostObjectId(@Param("hostObjectId") Integer hostObjectId);