Spring存储库自定义方法

时间:2017-07-28 22:21:50

标签: java spring repository spring-data-jpa

我正在尝试向spring数据存储库添加一些自定义功能。 使用它作为我的起点http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.single-repository-behaviour我创建了以下代码:

public interface TableLock<T> {
    void checkout(T entity);
    void checkin(T entity, boolean cmpltBatch);
}


public interface BatchTableLock extends TableLock<MyEntity> {

}

public class BatchTableLockImpl implements BatchTableLock {
    private static final Logger logger = LoggerFactory.getLogger(BatchTableLockImpl.class);
    @PersistenceContext(unitName = "mysql")
    private EntityManager em;

    @Override
    public void checkout(MyEntity batch) {
    Long id = batch.getMyEntityId();
    try {
        MyEntity p = em.find(MyEntity.class, id, LockModeType.PESSIMISTIC_WRITE);
        if (p == null) {
            logger.error("checkout : MyEntity id {} must be valid", id);
            throw new PessimisticLockException();
        }
        if (myCondition is true) {
            return;
        }
    } catch (LockTimeoutException | PessimisticLockException e) {
        logger.error("checkout : Unable to get write lock on MyEntity id {}", id, e);
    }
    throw new PessimisticLockException();
}

@Override
public void checkin(MyEntity batch, boolean cmplt) {
    Long id = batch.getMyEntityId();
    try {
        MyEntity p = em.find(MyEntity.class, id, LockModeType.PESSIMISTIC_WRITE);
        if (p == null) {
            logger.error("complete : MyEntity id {} must be valid", id);
            return;
        }
        if (this is true) {
            if (cmplt) {
                yep;
            } else {
                nope;
            }
        } else if (cmplt) {
            logger.error("complete: Unable to complete MyEntity {} with status.", id);
        }
    } catch (LockTimeoutException | PessimisticLockException e) {
        logger.error("complete : Unable to get write lock on MyEntity id {}", id, e);
    }
}

}

@Repository
public interface MyDao extends CrudRepository<MyEntity, BigInteger>, BatchTableLock  {
    ... My queries ...
}

不幸的是我收到以下错误:

org.springframework.data.mapping.PropertyReferenceException: No property checkin found for type MyEntity!

如果我没弄错的话,那意味着spring正在尝试根据方法'checkin'生成查询,并且在MyEntity中找不到名为'checkin'的字段。这是正确的,没有这样的领域。我如何让它停止这样做?根据上面的链接,我认为不应该尝试为此方法生成查询,但无论如何它似乎都在做。我可能会遗漏一些东西,通常是这种情况,但我不知道它是什么。

1 个答案:

答案 0 :(得分:2)

如您链接的参考文档部分所述,您需要一个实现自定义方法的MyDaoImpl类。我想最简单的方法是将BatchTableLockImpl重命名为或者只是创建一个扩展该类的空MyDaoImpl