JPA之抽象类与泛型接口

实体类抽象父类

@MappedSuperclass
@Data
public abstract class CommonEntity {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
  @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
  @Temporal(TemporalType.TIMESTAMP)
  @CreatedDate
  private Date createTime;

  @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
  @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
  @Temporal(TemporalType.TIMESTAMP)
  @LastModifiedDate
  private Date modifiedTime;
}

抽象接口层

@NoRepositoryBean
public interface BaseRepository<T extends CommonEntity, ID extends Serializable> extends Repository<T, ID> {

    /**
     * Deletes a managed entity.
     * @param id    The id of the deleted entity.
     * @return      an {@code Optional} that contains the deleted entity. If there
     *              is no entity that has the given id, this method returns an empty {@code Optional}.
     */
    Optional<T> deleteById(ID id);
}

实体接口

interface TodoRepository extends BaseRepository<Todo, Long> {

    List<Todo> findAll();

    /**
     * Finds todo entries by using the search term given as a method parameter.
     * @param searchTerm    The given search term.
     * @return  A list of todo entries whose title or description contains with the given search term.
     */
    @Query("SELECT t FROM Todo t WHERE " +
            "LOWER(t.title) LIKE LOWER(CONCAT('%',:searchTerm, '%')) OR " +
            "LOWER(t.description) LIKE LOWER(CONCAT('%',:searchTerm, '%')) " +
            "ORDER BY t.title ASC")
    List<Todo> findBySearchTerm(@Param("searchTerm") String searchTerm);

    Optional<Todo> findOne(Long id);

    void flush();

    Todo save(Todo persisted);
}

整体来说,扩展方式很多

猜你喜欢

转载自www.cnblogs.com/zhouwenyang/p/11136536.html