{"id":3213,"date":"2025-12-24T10:00:37","date_gmt":"2025-12-24T15:00:37","guid":{"rendered":"https:\/\/www.mymiller.name\/wordpress\/?p=3213"},"modified":"2025-12-24T10:00:37","modified_gmt":"2025-12-24T15:00:37","slug":"java-tips-part-4","status":"publish","type":"post","link":"https:\/\/www.mymiller.name\/wordpress\/java_tips\/java-tips-part-4\/","title":{"rendered":"Java Tips Part 4"},"content":{"rendered":"\n<p>Continuing my Java Tips from experience that I have learned from code reviews to different programming tasks.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"tip-16-perform-bulk-operations-with-native-queries-or-stored-procedure\">Tip 16: Perform Bulk operations with Native Queries, or Stored Procedure<\/h2>\n\n\n\n<p>It can be very tempting to do an update like the following:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>List&lt;Person&gt; people = ListUtils.safe(personRepository.findAll()).stream().filter person -&gt; person.getAge() &gt;= 60 ).map(person -&gt; {\n    person.setSeniorStatus(true);\n    return person;\n}).collect(Collectors.toList());\n\npersonRepository.saveAll(people);\n<\/code><\/pre>\n\n\n\n<p>However, doing this is more efficient than saving them one at a time.  However, it would be even more efficient to do something like:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>@Modifying\n@Query(\"update Person p set p.seniorStatus = 1 where p.age &gt;= 60\")\nvoid updateSeniorStatus();<\/code><\/pre>\n\n\n\n<p>Let the database perform the update across the tables.  The Database can perform this update easier and faster than performing it in Java code.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"tip-17-use-try-with-resources\">Tip 17: Use try-with-resources <\/h2>\n\n\n\n<p>While this is not a performance-enhancing action, it is a resource-handling enhancement.  Any object in Java that implements the AutoClosable interface can be used with the try-with resources. This guarantees any object created in the try, is properly closed when you exit the block.  The prevents resource leading. An example would be:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>static String readFirstLineFromFile(String path) throws IOException {\n    try (FileReader reader = new FileReader(path);\n         BufferedReader br =\n                   new BufferedReader(reader)) {\n        return br.readLine();\n    }\n}<\/code><\/pre>\n\n\n\n<p>This is extremely simple to illustrate that you can do multiple instantiations in the try field.  When this code exits they will be closed properly without you having to do so.  This could be extended with catch() and finally() blocks as well.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"tip-18-text-block-instead-of-string-concatentation\">Tip 18: Text Block instead of String concatentation<\/h2>\n\n\n\n<p>We&#8217;ve all had those big blocks of text in our code that we have to insert for some reason. Often we have done the following:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>String block = \"Lorem ipsum dolor sit amet, has id vide aliquid nominati, nulla inciderint his et. His nisl maluisset efficiendi in. Qui erant verear ei, nec ex ullum tantas epicurei. Has ne aperiam deserunt. Vis ne delenit repudiare, nec gubergren sadipscing ne. Purto placerat cu est, no ferri solum sit.\";<\/code><\/pre>\n\n\n\n<p>As one big long line that is difficult to read, because you have to keep scrolling to the right, or<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>String block = \"Lorem ipsum dolor sit amet, has id vide aliquid nominati,\"\n    + \" nulla inciderint his et. His nisl maluisset efficiendi in. Qui erant\"\n    + \" verear ei, nec ex ullum tantas epicurei. Has ne aperiam deserunt. Vis ne\"\n    + \" delenit repudiare, nec gubergren sadipscing ne. Purto placerat\"\n    + \" cu est, no ferri solum sit.\";<\/code><\/pre>\n\n\n\n<p>This generates no less than 9 String objects to create that String.  Well now we have a text block, this could be changed to the following:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>String block = \"\"\"\nLorem ipsum dolor sit amet, has id vide aliquid nominati, \\\nnulla inciderint his et. His nisl maluisset efficiendi in. \\\nQui erant verear ei, nec ex ullum tantas epicurei. Has \\\nne aperiam deserunt. Vis ne delenit repudiare, nec gubergren \\\nsadipscing ne. Purto placerat cu est, no ferri solum sit. \\\n\nIus ne quas choro, duo ad falli perpetua reformidans. Ne ius \\\npetentium philosophia. Id usu gloriatur contentiones, et elit \\\nminim duo, cetero noluisse partiendo usu id. Pro ei velit \\\nnostrud, pri choro dictas dissentiet ex.\\\n\"\"\";<\/code><\/pre>\n\n\n\n<p>That generates a single String object, if you do not want the new line characters where it appears in the block, inserting a &#8220;\\&#8221; .  The line above will get you 3 lines, with the 1st and 3rd being the text, and the 2nd a blank line.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"tip-19-cache-if-you-maintain-a-large-number-of-in-memory-object\">Tip 19: Cache if you maintain a large number of in-memory object<\/h2>\n\n\n\n<p>Sometimes you need to maintain a large in-memory set\/list\/map of objects, when that happens you need to look at making use of a <a href=\"https:\/\/www.mymiller.name\/wordpress\/programming\/java\/caching-objects\/\" data-type=\"post\" data-id=\"3225\">Cache<\/a>.  When you only need to keep a single instance of an object around, not every instance that is generated, then a cache maybe right for you. <\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"tip-20-entity-field-datecreated-and-lastupdated\">Tip 20: Entity field dateCreated and lastUpdated<\/h2>\n\n\n\n<p>Many may not think they need it, but it is a set of data that you can not generate if you don&#8217;t collect it to begin with.  When creating a database table, always add &#8220;date_created&#8221; and &#8220;last_updated&#8221; columns that are timestamps.  This helps track changes in the data.  Now in your Java code, when you create your entity class add this little tidbit:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>    @PrePersist\n    protected void onCreate() {\n        this.dateCreated = ZonedDateTime.now();\n    }\n\n    @PreUpdate\n    protected void onUpdate() {\n        this.lastUpdated = ZonedDateTime.now();\n    }<\/code><\/pre>\n\n\n\n<p>@PrePersist will set the timestamp for dateCreated when the item is first saved to the database.  While @PreUpdate will update the timestamp for lastUpdated every time the item is updated.  Make this a class that you derive all of your entities from and you a self-updating columns.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Continuing my Java Tips from experience that I have learned from code reviews to different programming tasks. Tip 16: Perform Bulk operations with Native Queries, or Stored Procedure It can be very tempting to do an update like the following: However, doing this is more efficient than saving them one at a time. However, it [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":3129,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_coblocks_attr":"","_coblocks_dimensions":"","_coblocks_responsive_height":"","_coblocks_accordion_ie_support":"","jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":true,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2}},"categories":[452],"tags":[69,361,362],"series":[360],"class_list":["post-3213","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java_tips","tag-java-2","tag-java-tips","tag-tips","series-java-tips"],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2021\/12\/sam-dan-truong-rF4kuvgHhU-unsplash-scaled-e1640791434235.jpg?fit=640%2C427&ssl=1","jetpack-related-posts":[{"id":3148,"url":"https:\/\/www.mymiller.name\/wordpress\/java_tips\/java-tips-part-2\/","url_meta":{"origin":3213,"position":0},"title":"Java Tips Part 2","author":"Jeffery Miller","date":"December 24, 2025","format":false,"excerpt":"Continuing my Java Tips from experience that I have learned from code reviews to different programming tasks. Tip 6: Don't call .toString() on slf4j logging calls. So if you're following my other tips and using the formatting option of the logging messages like this: list.parallelStream().filter(item -> !item.contains(\"BOB\")).forEach(item -> logger.debug(\"Item: {}\u2026","rel":"","context":"In &quot;Java Tips&quot;","block_context":{"text":"Java Tips","link":"https:\/\/www.mymiller.name\/wordpress\/category\/java_tips\/"},"img":{"alt_text":"","src":"https:\/\/i0.wp.com\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2021\/12\/sam-dan-truong-rF4kuvgHhU-unsplash-scaled-e1640791434235.jpg?fit=640%2C427&ssl=1&resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2021\/12\/sam-dan-truong-rF4kuvgHhU-unsplash-scaled-e1640791434235.jpg?fit=640%2C427&ssl=1&resize=350%2C200 1x, https:\/\/i0.wp.com\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2021\/12\/sam-dan-truong-rF4kuvgHhU-unsplash-scaled-e1640791434235.jpg?fit=640%2C427&ssl=1&resize=525%2C300 1.5x"},"classes":[]},{"id":3185,"url":"https:\/\/www.mymiller.name\/wordpress\/java_tips\/java-tips-part-3\/","url_meta":{"origin":3213,"position":1},"title":"Java Tips Part 3","author":"Jeffery Miller","date":"December 24, 2025","format":false,"excerpt":"Continuing my Java Tips from experience that I have learned from code reviews to different programming tasks. Tip 11: Use Hibernate Statistics Now, this is only for your development profiles\/environments, not for production. Hibernate has built-in statistics on your queries. This will break down how much time is spent along\u2026","rel":"","context":"In &quot;Java Tips&quot;","block_context":{"text":"Java Tips","link":"https:\/\/www.mymiller.name\/wordpress\/category\/java_tips\/"},"img":{"alt_text":"","src":"https:\/\/i0.wp.com\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2021\/12\/sam-dan-truong-rF4kuvgHhU-unsplash-scaled-e1640791434235.jpg?fit=640%2C427&ssl=1&resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2021\/12\/sam-dan-truong-rF4kuvgHhU-unsplash-scaled-e1640791434235.jpg?fit=640%2C427&ssl=1&resize=350%2C200 1x, https:\/\/i0.wp.com\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2021\/12\/sam-dan-truong-rF4kuvgHhU-unsplash-scaled-e1640791434235.jpg?fit=640%2C427&ssl=1&resize=525%2C300 1.5x"},"classes":[]},{"id":3249,"url":"https:\/\/www.mymiller.name\/wordpress\/java_tips\/java-tips-part-5\/","url_meta":{"origin":3213,"position":2},"title":"Java Tips Part 5","author":"Jeffery Miller","date":"December 24, 2025","format":false,"excerpt":"Tip 21: Use Prepared Statements When working with JPA\/Hibernate make use of Prepared Statements that can be reused. Basically, I'm saying do not do the following: Query query = JPA.em().createNativeQuery(\"select count(*) from user u inner join\" + \"address a where a.user_id=u.id and a.city='\" + city + \"'\"); BigInteger val =\u2026","rel":"","context":"In &quot;Java Tips&quot;","block_context":{"text":"Java Tips","link":"https:\/\/www.mymiller.name\/wordpress\/category\/java_tips\/"},"img":{"alt_text":"","src":"https:\/\/i0.wp.com\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2021\/12\/sam-dan-truong-rF4kuvgHhU-unsplash-scaled-e1640791434235.jpg?fit=640%2C427&ssl=1&resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2021\/12\/sam-dan-truong-rF4kuvgHhU-unsplash-scaled-e1640791434235.jpg?fit=640%2C427&ssl=1&resize=350%2C200 1x, https:\/\/i0.wp.com\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2021\/12\/sam-dan-truong-rF4kuvgHhU-unsplash-scaled-e1640791434235.jpg?fit=640%2C427&ssl=1&resize=525%2C300 1.5x"},"classes":[]},{"id":3111,"url":"https:\/\/www.mymiller.name\/wordpress\/java_tips\/java-tips-part-1\/","url_meta":{"origin":3213,"position":3},"title":"Java Tips Part 1","author":"Jeffery Miller","date":"December 24, 2025","format":false,"excerpt":"Over the years I have done a number of code reviews there have been a number of common mistakes that I have found. So here are my Java tips a series of posts going over these tips. Tip 1: Throw original Exception Many times in our code we will catch\u2026","rel":"","context":"In &quot;Java Tips&quot;","block_context":{"text":"Java Tips","link":"https:\/\/www.mymiller.name\/wordpress\/category\/java_tips\/"},"img":{"alt_text":"","src":"https:\/\/i0.wp.com\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2021\/12\/sam-dan-truong-rF4kuvgHhU-unsplash-scaled-e1640791434235.jpg?fit=640%2C427&ssl=1&resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2021\/12\/sam-dan-truong-rF4kuvgHhU-unsplash-scaled-e1640791434235.jpg?fit=640%2C427&ssl=1&resize=350%2C200 1x, https:\/\/i0.wp.com\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2021\/12\/sam-dan-truong-rF4kuvgHhU-unsplash-scaled-e1640791434235.jpg?fit=640%2C427&ssl=1&resize=525%2C300 1.5x"},"classes":[]},{"id":2391,"url":"https:\/\/www.mymiller.name\/wordpress\/java_tips\/java-development-tips\/","url_meta":{"origin":3213,"position":4},"title":"Java Development Tips","author":"Jeffery Miller","date":"December 23, 2025","format":false,"excerpt":"Java-based servers or applications often have to deal with large amounts of data.\u00a0 Whether the data is from a database, or from a local file, processing this data in an efficient manner is a priority for maintainability. In this article, we will discuss the types of Java Data Objects and\u2026","rel":"","context":"In &quot;Java Tips&quot;","block_context":{"text":"Java Tips","link":"https:\/\/www.mymiller.name\/wordpress\/category\/java_tips\/"},"img":{"alt_text":"","src":"https:\/\/i0.wp.com\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2018\/10\/archive-1850170_640.jpg?fit=640%2C426&ssl=1&resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2018\/10\/archive-1850170_640.jpg?fit=640%2C426&ssl=1&resize=350%2C200 1x, https:\/\/i0.wp.com\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2018\/10\/archive-1850170_640.jpg?fit=640%2C426&ssl=1&resize=525%2C300 1.5x"},"classes":[]},{"id":2409,"url":"https:\/\/www.mymiller.name\/wordpress\/lambda_stream\/java-getter-setter-used-as-lamdas\/","url_meta":{"origin":3213,"position":5},"title":"Java getter\/setter used as Lamda&#8217;s","author":"Jeffery Miller","date":"December 23, 2025","format":false,"excerpt":"Once again I'm looking into ways to make coding so much easier. I needed to be able to pass in a Class::get and a Class:set as a Lamda in order to be able to reuse code across types. It's a rather simple process. However I have not found it really\u2026","rel":"","context":"In &quot;Lambda's and Streams&quot;","block_context":{"text":"Lambda's and Streams","link":"https:\/\/www.mymiller.name\/wordpress\/category\/lambda_stream\/"},"img":{"alt_text":"","src":"https:\/\/i0.wp.com\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2018\/10\/coffee-cup-2317201_640.jpg?fit=640%2C426&ssl=1&resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2018\/10\/coffee-cup-2317201_640.jpg?fit=640%2C426&ssl=1&resize=350%2C200 1x, https:\/\/i0.wp.com\/www.mymiller.name\/wordpress\/wp-content\/uploads\/2018\/10\/coffee-cup-2317201_640.jpg?fit=640%2C426&ssl=1&resize=525%2C300 1.5x"},"classes":[]}],"jetpack_sharing_enabled":true,"jetpack_likes_enabled":true,"_links":{"self":[{"href":"https:\/\/www.mymiller.name\/wordpress\/wp-json\/wp\/v2\/posts\/3213","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.mymiller.name\/wordpress\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.mymiller.name\/wordpress\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.mymiller.name\/wordpress\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.mymiller.name\/wordpress\/wp-json\/wp\/v2\/comments?post=3213"}],"version-history":[{"count":12,"href":"https:\/\/www.mymiller.name\/wordpress\/wp-json\/wp\/v2\/posts\/3213\/revisions"}],"predecessor-version":[{"id":3247,"href":"https:\/\/www.mymiller.name\/wordpress\/wp-json\/wp\/v2\/posts\/3213\/revisions\/3247"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.mymiller.name\/wordpress\/wp-json\/wp\/v2\/media\/3129"}],"wp:attachment":[{"href":"https:\/\/www.mymiller.name\/wordpress\/wp-json\/wp\/v2\/media?parent=3213"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.mymiller.name\/wordpress\/wp-json\/wp\/v2\/categories?post=3213"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.mymiller.name\/wordpress\/wp-json\/wp\/v2\/tags?post=3213"},{"taxonomy":"series","embeddable":true,"href":"https:\/\/www.mymiller.name\/wordpress\/wp-json\/wp\/v2\/series?post=3213"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}