2016-09-06 56 views
0

我有弹簧数据jpa repository.I该实体包含主键id int和ipaddress字符串。该表一次只包含1条记录,否则为空。 如何使用JPA检索记录,如果未找到,则返回null。使用Spring Data检索记录JPA

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

使用'findAll()'和管理你自己在你的服务中的空转换,或者写一个查询。 –

回答

0

根据该命名约定,则应该与名称findById(Integer id)(假设Id是主键)

+0

我不想像传递主键那样做。如果一些主键被改变了,那么我必须再次更改代码。 – boycod3

0

假设有一个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(); 



} 
+0

显示'antlr.NoViableAltException:意外的标记:*' – boycod3

+0

将@Query(“SELECT * FROM a limit 1;”)'改为'@Query(“SELECT a FROM a limit 1;”)'它应该可以工作。 – sz4b0lcs

+0

你可以像@ sz4b0lcs所说的那样做,或者你可以在你的实体/域类中使用'@Table(name =“a”)'来定义表名,来命名数据库中形成的表 –