The native SQL query we want to map in JPA is similar to the following:

select *
from PARTNER
where EVENT_TIMESTAMP >= timestamp '2021-09-17 10:00:00'
  and EVENT_TIMESTAMP < timestamp '2021-09-17 11:00:00'

where the two timestamps should come as query parameters.

With JPA you can use a TypedQuery for example and set the LocalDateTime values to query parameters via the setParameter method:

@Stateless
public class PartnerDataRepository {

    @Inject private EntityManager em;

    public List<PartnerData> findPartnerDataWithinInterval(
      LocalDateTime fromDatetime, LocalDateTime toDatetime) {
        TypedQuery<PartnerData> query =
            em.createNamedQuery(
                PartnerData.FIND_PARTNER_DATA_IN_TIME_INTERVAL, PartnerData.class);

        query.setParameter(PartnerData.FROM_DATETIME, fromDatetime);
        query.setParameter(PartnerData.TO_DATETIME, toDatetime);

        return query.getResultList();
    }
}

In the named query itself you can directly pass the parameters before : as usual, and the implementation (in my case Hibernate) takes care of the rest :

@Entity
@Access(AccessType.FIELD)
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@Table(name = PartnerData.TABLE_NAME)
@NamedQueries({
 @NamedQuery(
      name = PartnerKerndaten.FIND_PARTNER_DATA_IN_TIME_INTERVAL,
      query = "select m from PartnerData m where eventTimestamp >= :fromDatetime and eventTimestamp < :toDatetime")
})
public class PartnerData {
  public static final String TABLE_NAME = "PARTNER";

  public static final String FROM_DATETIME = "fromDatetime";
  public static final String TO_DATETIME = "toDatetime";

  public static final String FIND_PARTNER_DATA_IN_TIME_INTERVAL =
      "findPartnerDataWithinInterval";

  //... rest ignored for brevity
}

Shared with from Codever. 👉 Use the Copy to mine functionality to copy this snippet to your own personal collection and easy manage your code snippets.

Codever is open source on Github ⭐🙏

Use parse method and apply withNano with value 0 seconds on the result

final var fromDateTime = LocalDateTime.parse("2017-02-26T01:02:03").withNano(0);

Shared with from Codever. 👉 Use the Copy to mine functionality to copy this snippet to your own personal collection and easy manage your code snippets.

Codever is open source on Github ⭐🙏

At Codever we use Angular extensively, and many time the use navigates to certain routes where dynamically content based on an id for example is loaded. To access these path params in angular navigation you have two possibilities.

The first one, asynchronous, is to subscribe to the Observable<ParamMap> observable, which you can access via paramMap method of the ActivatedRoute. Then use the get method with parameter you want to get as argument, as in the example below in the ngOnInit method:

// other imports not included for brevity
import { ActivatedRoute } from '@angular/router';
import { switchMap } from 'rxjs/operators';

@Component({
  selector: 'app-public-snippet-details',
  templateUrl: './public-snippet-details.component.html'
})
export class PublicSnippetDetailsComponent implements OnInit {
  snippetId: string;
  snippet$: Observable<Codelet>;

  constructor(
    private publicSnippetsService: PublicSnippetsService,
    private userInfoStore: UserInfoStore,
    private route: ActivatedRoute) {
  }

  ngOnInit() {
    this.snippet$ = this.route.paramMap.pipe(
      switchMap(params => {
        this.snippetId = params.get('id');
        return this.publicSnippetsService.getPublicSnippetById(this.snippetId);
      })
    );
  }

}

The second one, synchronous, is to the snapshot of this route (ActivatedRoute), and directly access the parameter from the paramMap, const bookmarkId = this.route.snapshot.paramMap.get('id');

export class BookmarkDetailsComponent implements OnInit {
  // constructor and other details ignored for brevity

  ngOnInit() {
    this.popup = this.route.snapshot.queryParamMap.get('popup');
    this.userInfoStore.getUserInfo$().subscribe(userInfo => {
      this.userData$ = this.userDataStore.getUserData$();
      this.bookmark = window.history.state.bookmark;
      if (!window.history.state.bookmark) {
        const bookmarkId = this.route.snapshot.paramMap.get('id');
        this.personalBookmarksService.getPersonalBookmarkById(userInfo.sub, bookmarkId).subscribe((response) => {
          this.bookmark = response;
        });
      }
    });
  }
}

Reference - https://angular.io/guide/router


Shared with from Codever. 👉 Use the Copy to mine functionality to copy this snippet to your own personal collection and easy manage your code snippets.

Codever is open source on Github ⭐🙏

When you are searching your code snippets on Codever, depending on the search terms you use, relevant results are displayed. Behind this there is a MongoDb full text search index. Let’s see how it is created and used.

Full text search is supported in Mongo by using a text index. Text indexes can include any field whose value is a string or an array of string elements, to which you can give weights. For a text index, the weight of an indexed field denotes the significance of the field relative to the other indexed fields in terms of the text search score.

db.snippets.createIndex(
  {
    title: "text",
    tags: "text",
    "codeSnippets.comment": "text",
    "codeSnippets.code": "text",
    sourceUrl: "text"
  },
  {
    weights: {
      title: 8,
      tags: 13,
      "codeSnippets.comment": 3,
      "codeSnippets.code": 1,
      sourceUrl: 1
    },
    name: "full_text_search",
    default_language: "none",
    language_override: "none"
  }
);

For each indexed field in the document, MongoDB multiplies the number of matches by the weight and sums the results. Using this sum, MongoDB then calculates the score for the document. You then can use the $meta operator for details on returning and sorting by text scores, as in the snippet below:

let getPublicBookmarksForSearchedTerms = async function (nonSpecialSearchTerms, page, limit, sort, specialSearchFilters, searchInclude) {

  let filter = {
    public: true
  }

  if ( nonSpecialSearchTerms.length > 0 ) {
    if(searchInclude === 'any') {
      filter.$text = {$search: nonSpecialSearchTerms.join(' ')}
    } else {
      filter.$text = {$search: bookmarksSearchHelper.generateFullSearchText(nonSpecialSearchTerms)};
    }
  }

  addSpecialSearchFiltersToMongoFilter(specialSearchFilters, filter);

  let sortBy = {};
  if ( sort === 'newest' ) {
    sortBy.createdAt = -1;
  } else {
    sortBy.score = {$meta: "textScore"}
  }

  let bookmarks = await Bookmark.find(
    filter,
    {
      score: {$meta: "textScore"}
    }
  )
    .sort(sortBy)
    .skip((page - 1) * limit)
    .limit(limit)
    .lean()
    .exec();

  return bookmarks;
}

Reference - https://docs.mongodb.com/manual/core/index-text/


Shared with from Codever. 👉 Use the Copy to mine functionality to copy this snippet to your own personal collection and easy manage your code snippets.

Codever is open source on Github ⭐🙏

In Codever we use extensively the Angular Http Client to make REST calls against a NodeJs/ExpressJS API - source code on Github.

In the following snippet you can see hot to set http query parameters to the rest api calls.

Use the HttpParams class with the params request option to add URL query strings in your HttpRequest:

  getFilteredPersonalBookmarks(searchText: string, limit: number, page: number, userId: string, include: string): Observable<Bookmark[]> {
    const params = new HttpParams()
      .set('q', searchText)
      .set('page', page.toString())
      .set('limit', limit.toString())
      .set('include', include);
    return this.httpClient.get<Bookmark[]>(`${this.personalBookmarksApiBaseUrl}/${userId}/bookmarks`,
      {params: params})
      .pipe(shareReplay(1));
  }

Reference - https://angular.io/guide/http#url-params


Shared with from Codever. 👉 Use the Copy to mine functionality to copy this snippet to your own personal collection and easy manage your code snippets.

Codever is open source on Github ⭐🙏