Sep 11, 2018

A Java Stream to UPDATE a Subset of Columns

The Stream ORM Speedment has received a nice feature in the latest release. While traditionally focused on accelerating database reads, Speedment has always also had database write functionality. In the latest version a much anticipated feature has been added - the ability to determine a subset of columns to update.

The Streams API Goes Both Ways

Persisting data in Speedment follows the same intuitive stream approach as other Speedment data oriented operations. Just as querying the database is expressed as a stream of operations on data items, the POJO entities received from the database may be persisted to the database by simply terminating the stream in a database persister.

Simple retrieval of data can be expressed as


Optional<Film> longFilm = films.stream()
    .filter(Film.LENGTH.greaterThan(120))
    .findAny();
which will find a POJO representing a row in the underlying database for which the supplied predicate holds true. In this case, the user will get a film longer than two hours, if any such film exists. For reading data, Speedment thus supplies a stream source that represents the database, in this case the films instance which runs code generated by Speedment. Analogously, Speedment defines a stream termination that handles data writing which can be used as follows.

Stream.of("Italiano", "Español")
        .map(ln -> new LanguageImpl().setName(ln))
        .forEach(languages.persister());
Here we create a stream of POJOs representing rows in the database that may not yet exist in the database. The languages instance on line 3 is a Manager just like films above and is implemented by code generated by Speedment. The persister() method returns a Consumer of POJOs that will persist the items to the database.

Notice the symmetry where Speedment has generated code handling reading and writing of database data as intuitive Stream operations.

Updating Data in a Single Stream

Since Speedment provides a consistent API of treating database operations as stream operations on POJOs, the reading and writing of data can be composed and combined freely. Thus, a POJO retrieved from a Speedment source is the very same kind of POJO that is needed for persistence. Therefore, it makes a lot of sense to use streams that have both source and termination defined by Speedment. If one for example would like to update some rows of a table of the database, this can be done in the following concise way.

  languages.stream()
        .filter(Language.NAME.equal("Deutsch"))
        .map(Language.NAME.setTo("German"))
        .forEach(languages.updater());
Almost self-explanatory, at least compared to the corresponding JDBC operations, the code above will find any Language named “Deutsch” in the database and rename it to “German”. The terminating operation here is the updater which in contrast to the persister modifies existing rows of the database.

Selecting the Fields to Update

The basic updater will update all relevant columns of the row in question, which makes sense in many cases. However, for the case above when updating a single column of the database this behaviour may be wasteful or even prone to errors.

Even if the code above intends to update only the name of the language, since the updater updates all columns of the row it will actually update the name to a new value and also reset all other columns to the values they had when the POJO was created from the database. If this code is the sole actor modifying the database this may be a minor problem, but in a concurrent environment it may create undesired race conditions where this innocent update of a single field may happen to undo changes to other columns.

In Speedment 3.1.6 and later, the user may select which fields to update and persist by supplying a description of the desired fields of the POJO. To improve on the last example, the following code will update only the name of the Language.


   Updater<Language> updater = languages.updater(FieldSet.of(Language.NAME)); 
   languages.stream()
        .filter(Language.NAME.equal("Deutsch"))
        .map(Language.NAME.setTo("German"))
        .forEach(updater);
There are elaborate ways to express the set of fields to update and the interested reader is encouraged to learn more from the Speedment User Guide and to get a free license and example project scaffolding at the initializer.

18 comments:

  1. These days, it is hard to appreciate the things and when the general population wind up old they need to invest their energy with the exceptional individuals. Some days I will likewise wind up old and I am considering my future and students can best writing services online to get quality work. This is so decent article for me.

    ReplyDelete
  2. It is a great website.. The Design looks very good.. Keep working like that!. villas for sale puerto banus

    ReplyDelete
  3. Sale and Rent on the Costa del Sol, such as: Luxury VILLAS FOR SALE IN NUEVA ANDALUCIA SpainForSale.Properties is considered one of the most trusted Exclusive Real Estate Agencies in Marbella, Costa del Sol and other “Prime Locations” in Spain.Some of the features include: fitted wardrobes in all bedrooms, marble floors, underfloor heating, 2 secure underground parking spaces, large storeroom, individually controlled hot & cold air conditioning, 24 hour security, etc.
    Apartments for sale in Marbella, Spain.
    Properties for sale Marbella, Spain.
    Apartment for rent in Marbella, Spain.
    Location, Location, Location! Price 675,000€ This beautiful apartment has just been completely refurbished to a very modern contemporary home. Spacious, open plan, bright, light, and extremely elegant. 2 bedrooms, 2 bathrooms, brand new kitchen leading onto a utility room. There is an office off the master bedroom and a terrace off the guest bedroom. The lounge has stucco walls, and the terrace off the lounge is large and south facing, overlooking the decorative fountains and water features, along with hundreds of species of plants, flowers and trees from all over the world, these can be admired from every corner and by strolling through the path ways that wind throughout the gardens. A garage space is included in the sales price. One of the most attractive characteristics of La Alcazaba has to be the unbeatable location. Only a short stroll (100mts) to the gorgeous sandy beaches and the fantastic promenade that connects Marbella to Puerto Banús, and which can be enjoyed by everyone whether you like to walk, run or cycle, while taking in the sea air and marvellous views all the way. Perhaps too, savouring food and drink in any of the many beach restaurants along the way!!
    Apartments for sale in Marbella, Spain.
    Properties for sale Marbella, Spain.
    Apartment for rent in Marbella, Spain.
    A wonderful 3-rd floor apartment with fabulous views of the sea up to Gibraltar, located only a short walk to the beach, and to the world famous yacht harbour of Puerto Banús. The fully gated, luxurious complex has 24-hour security service and enjoys beautifully maintained gardens with swimming pool, and a separate spa building with indoor swimming pool, sauna & gymnasium. This accommodation comprises: hall; fully equipped kitchen with Siemens appliances and with a separate laundry room; very spacious living/dining room with access to a large southeast-facing terrace with magnificent sea views; 3 en-suite bedrooms, all with wooden floors, the master bedroom with walk-in wardrobe and 2 bedrooms with access to the terrace; guest toilet. Individual hot/cold air-conditioning. 2 parking spaces and a storage room in the underground garage are included. A great location close to everything!

    ReplyDelete
  4. Marbella, apartment for sale.
    Apartments for sale in Marbella, Spain.
    Villas for sale in Marbella, Spain.
    Townhouses for sale in Marbella, Spain.
    Properties for sale Marbella, Spain.
    Apartment for rent in Marbella, Spain.
    WE ARE FULLY LICENSED! 1st Occupancy licence in place block 23
    FROM ONLY 345.000€ LUXURY SEA VIEWS APARTMENTS. Gated and secure community in El Paraiso Alto-La Alquería.Spacious living areas with luxury fittings. Large terraces with breath-taking sea & coastal views. Exceptional qualities and Gaggenau kitchens. Communal swimming pool and mature gardens. Underground parking spaces and storages. Amazing show flat ready for viewings!. First occupancy license in place block 23
    Apartments for sale in Marbella, Spain.
    Properties for sale Marbella, Spain.
    Apartment for rent in Marbella, Spain.
    Recently renovated apartment located in a gated community with 24-hour security in Aloha, Nueva Andalucia. The property comprises: entrance hall; bright and spacious living-dining room with access to the covered terrace; en-suite master bedroom; two further guest bedrooms sharing a bathroom; and a guest toilet. Extra features include: A/C hot and cold; wooden floors; private parking space and storage room. The community offers: indoor and outdoor swimming pool; Gym; landscaped gardens and 24-hour security. Great family home for all year round living in the heart of the golf valley nearby all amenities such as bars, restaurants, shops, banks and within a 5-minute drive to Puerto Banus.
    Apartments for sale in Marbella, Spain.
    Properties for sale Marbella, Spain.
    Apartment for rent in Marbella, Spain.
    Second-line beach, partly renovated duplex penthouse with sea views in Marina Puente Romano. This south-facing penthouse is distributed over 2 levels and comprises, on entrance level: spacious living/dining room with access to a covered terrace; fully fitted modern kitchen with Siemens appliances; 2 en-suite bedrooms, one with access to front terrace; and guest toilet. Upstairs: lounge with access to a spectacular terrace on a split level with plunge pool, enjoying views to the Mediterranean coast; terrace with mountain views at the back of the property; master bedroom with access to the terrace and with large en-suite modern bathroom with bath and walk-in shower. Sale and Rent on the Costa del Sol, such as: Luxury PLOTS FOR SALE MARBELLA SpainForSale.Properties is considered one of the most trusted Exclusive Real Estate Agencies in Marbella, Costa del Sol and other “Prime Locations” in Spain.
    Properties for sale Marbella, Spain.
    Apartment for rent in Marbella, Spain.

    ReplyDelete
  5. Great content material and great layout. Your website deserves all of the positive feedback it’s been getting. plattvärmeväxlare

    ReplyDelete
  6. CLF-C01 Questions Answers Exact2Pass study guides, dumps and practice questions and answers provide you worthwhile help for the preparation of your exam syllabus; both in practical and theoretical terms.

    ReplyDelete
  7. This is a nice article here with some useful tips for those who are not used-to comment that frequently. Thanks for this helpful information I agree with all points you have given to us. I will follow all of them.
    Advanced Java online training
    Salesforce online training

    ReplyDelete
  8. This comment has been removed by the author.

    ReplyDelete
  9. Positive site, where did u come up with the information on this posting?I have read a few of the articles on your website now, and I really like your style. Thanks a million and please keep up the effective work.
    python training in chennai

    python course in chennai

    python online training in chennai

    python training in bangalore

    python training in hyderabad

    python online training

    python training

    python flask training

    python flask online training

    python training in coimbatore

    ReplyDelete
  10. Great article, I follow your instruction to updates and which increases the speed of the device and get many latest features. Thanks to sharing with us. best video editing software used by YouTubers
    best free video editing softwaresthese are nice applications.

    ReplyDelete
  11. Cubase Pro Crack Mac follows the highly anticipated historical release with many major improvements, inspiring tools, and major workflow improvements.
    Youtube by Click Crack
    GOM Player Plus Crack
    reFX Nexus Crack

    ReplyDelete
  12. We at thesis writing help have started working with understudies by conveying them journal write my assignment uk, which not just assists understudies with composing their exploration papers yet helps them in the article distributing process also.

    ReplyDelete
  13. Baccarat - Worrington, VA: Free online betting tips - Wolverrington
    Free Betting Tips For Today & 카지노사이트 Weekend's 바카라 Matches - Bet on football, tennis, horse racing and all bk8 sports from across the UK.

    ReplyDelete
  14. If you're in need of foundation repair Edmonton , look no further than Rammafoundation. We're a trusted authority on all things foundation related and we'll be more than happy to help you get your life back on track. From fixing dry, cracked or peeling foundations to restoring discoloured areas, we have the expertise and experience to get the job done right. We also offer a wide range of services to meet your specific needs, so don't hesitate to give us a call today!

    ReplyDelete
  15. Free Letcracksetup Full Latest Version Download Here
    Letcracksetup

    ReplyDelete