Skip to content
Konstantin Triger edited this page May 29, 2020 · 9 revisions

Started in Fundamentals, we continue writing tutorial samples with FluentJPA.

PostgreSQL INSERT

Other basic clauses: SELECT, UPDATE, DELETE

insert multiple rows

FluentQuery query = FluentJPA.SQL((Link link) -> {

    INSERT().INTO(viewOf(link, Link::getUrl, Link::getName));
    VALUES(row("http://www.google.com", "Google"),
           row("http://www.yahoo.com", "Yahoo"),
           row("http://www.bing.com", "Bing"));
});

batch insert

List<Link> links = ... //external parameter

FluentQuery query = FluentJPA.SQL((Link link) -> {

    View<Link> viewOfLink = viewOf(link, Link::getUrl, Link::getName,
                                         l -> l.getStore().getId());

    INSERT().INTO(viewOfLink);
    VALUES(viewOfLink.from(links));
});

insert date

FluentQuery query = FluentJPA.SQL((Link link) -> {

    INSERT().INTO(viewOf(link, Link::getUrl, Link::getName, Link::getLastUpdate));
    VALUES(row("http://www.facebook.com", "Facebook", DATE.of("2013-06-01")));
});

insert Object

If some fields should not be takes from the object, they should be put at the end of the view. Then they can be overridden:

Link toInsert = ... //external parameter
int storeId = ... //external parameter

FluentQuery query = FluentJPA.SQL((Link link) -> {

    View<Link> viewOfLink = viewOf(link, Link::getUrl, Link::getName,
                                                       l -> l.getStore().getId(),
                                                       Link::getLastUpdate);
    INSERT().INTO(viewOfLink);
    VALUES(viewOfLink.from(toInsert, storeId, DEFAULT()));
    // overrides come at the end  ---^^^^^^^^^^^^^^^^^^
    // I.e. FluentJPA starts populating from the end,
    // and rest of parameters "takes" from the entity
    // (url and name in this example)
});

insert data from another table (bulk insert)

// same structure - derivation
@Tuple
@Table(name = "link_tmp")
public static class LinkTmp extends Link {
}

FluentQuery query = FluentJPA.SQL((LinkTmp linkTmp,
                                   Link link) -> {
    INSERT().INTO(linkTmp);
    SELECT(link);
    FROM(link);
    WHERE(link.getLastUpdate() != null);
});