如何在Spring Data JPA的JpaRepository中创建自定义方法?

huangapple 未分类评论57阅读模式
标题翻译

How to make a custom method in JpaRepository from Spring Data JPA?

问题

我正在使用Spring Data JPA的JpaRepository来调用MySQL数据库我知道我不需要添加findByIdsave等方法因为它们已经被Spring实现了但是我想要添加一个方法:`findByAccountNumber()`,但我不知道该如何做

我尝试了以下的方式但不起作用

@Repository
public interface AccountRepository extends JpaRepository<Account, Long> {

    Account findByAccountNumber(String accountNumber);
}

Account类

@Builder
@AllArgsConstructor
@NoArgsConstructor
@Data
@Entity
@Table(name = "account")
public class Account {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "accountId")
    private Long accountId;

    @Column(name = "accountNumber")
    private String accountNumber;

    @Column(name = "currentBalance")
    private BigDecimal currentBalance;
}

因此当我调用`accountRepository.findByAccountNumber(accountNumber)`我收到null的返回

CREATE TABLE `account` (
  `accountId` bigint(19) NOT NULL AUTO_INCREMENT,
  `accountNumber` varchar(100) NOT NULL,
  `currentBalance` decimal(10,5) NOT NULL,
  PRIMARY KEY (`accountId`)
)

我该如何创建这个方法谢谢
英文翻译

I'm using JpaRepository from Spring Data JPA to call a MySQL db. I know that I don't need to add metods for findById, save, etc becuse they are implemented by Spring, but I want to add a method: findByAccountNumber() and I don't know how to do that.

I tried to do in this way but it's not working:

@Repository
public interface AccountRepository extends JpaRepository&lt;Account, Long&gt; {

    Account findByAccountNumber(String accountNumber);
}

Account class:

@Builder
@AllArgsConstructor
@NoArgsConstructor
@Data
@Entity
@Table(name = &quot;account&quot;)
public class Account {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = &quot;accountId&quot;)
    private Long accountId;

    @Column(name = &quot;accountNumber&quot;)
    private String accountNumber;

    @Column(name = &quot;currentBalance&quot;)
    private BigDecimal currentBalance;
}

So when I'm calling accountRepository.findByAccountNumber(accountNumber) I receive null.

CREATE TABLE `account` (
  `accountId` bigint(19) NOT NULL AUTO_INCREMENT,
  `accountNumber` varchar(100) NOT NULL,
  `currentBalance` decimal(10,5) NOT NULL,
  PRIMARY KEY (`accountId`)
)

How can I make this method? Thank you!

答案1

得分: -1

也许你需要添加 org.springframework.data.repository.query.Param 注解。

Account findByAccountNumber(@Param("accountNumber") String accountNumber);
英文翻译

Maybe you need to add the org.springframework.data.repository.query.Param annotation.

Account findByAccountNumber(@Param(&quot;accountNumber&quot;) String accountNumber);

huangapple
  • 本文由 发表于 2020年5月31日 02:25:46
  • 转载请务必保留本文链接:https://java.coder-hub.com/62106943.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定