【问题标题】:Retrieve the record using Spring Data JPA使用 Spring Data JPA 检索记录
【发布时间】:2017-01-13 10:31:22
【问题描述】:

我有 spring 数据 jpa 存储库。我的实体包含主键 id int 和 ipaddress 字符串。该表一次仅包含 1 条记录,否则为空。 我如何使用 JPA 检索记录,如果找不到返回 null。

        @Repository
        public interface IpConfigRepository extends   JpaRepository<IpConfig, Integer> {
         //
         IpConfig findIpConfig();
        }

【问题讨论】:

  • 使用findAll()并在您的服务中自己管理空转换,或编写查询。

标签: spring-boot spring-data-jpa


【解决方案1】:

根据命名约定,您应该使用名称 findById(Integer id) 定义方法(假设 Id 为主键)

【讨论】:

  • 我不想像传递主键那样做。如果一些主键是如何更改的,那么我必须再次更改代码。
【解决方案2】:

假设你有一个如下所示的 A 类

   class A{
       private int id;
       private String data;

       // getters and setters

   }

您现在可以通过以下方式搜索项目。

public interface ARepo extends JpaRepository<A,Integer>{

  // get all the records from table. 
  List<A> findAll();

  // find record by id
  A findById(int id);

  // find record by data
  A findByData(String data);

  // find by date created or updated
  A findByDateCreated(Date date);

  // custom query method to select only one record from table
  @Query("SELECT * FROM a limit 1;")
  A findRecord();



}

【讨论】:

  • 显示antlr.NoViableAltException: unexpected token: *
  • @Query("SELECT * FROM a limit 1;") 更改为@Query("SELECT a FROM A a limit 1;"),它应该可以工作。
  • 您可以按照@sz4b0lcs 中的说明进行操作,也可以在实体/域类中使用@Table(name="a") 定义表名来命名数据库中形成的表
猜你喜欢
  • 2016-12-07
  • 1970-01-01
  • 1970-01-01
  • 2017-06-20
  • 1970-01-01
  • 1970-01-01
  • 2017-11-07
  • 1970-01-01
  • 2018-02-26
相关资源
最近更新 更多