<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Luan Vu on Medium]]></title>
        <description><![CDATA[Stories by Luan Vu on Medium]]></description>
        <link>https://medium.com/@luanvv?source=rss-168e44be4c62------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*w_B0Vla7bMY3wXPDagJ10w.jpeg</url>
            <title>Stories by Luan Vu on Medium</title>
            <link>https://medium.com/@luanvv?source=rss-168e44be4c62------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 12:18:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@luanvv/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[ArrayList and LinkedList in Java. Why I have never used LinkedList]]></title>
            <link>https://luanvv.medium.com/arraylist-and-linkedlist-in-java-why-i-have-never-used-linkedlist-fbaf46ddc350?source=rss-168e44be4c62------2</link>
            <guid isPermaLink="false">https://medium.com/p/fbaf46ddc350</guid>
            <category><![CDATA[linkedlist-in-java]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[arraylist-vs-linkedlist]]></category>
            <category><![CDATA[arraylist]]></category>
            <category><![CDATA[lists]]></category>
            <dc:creator><![CDATA[Luan Vu]]></dc:creator>
            <pubDate>Fri, 03 Nov 2023 10:50:40 GMT</pubDate>
            <atom:updated>2023-11-03T13:15:47.029Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*Z8sdk9wUiL1JV6kj.png" /></figure><p>List is a very commonly used collection in Java, especially ArrayList and LinkedList. Have you ever wondered the difference between these two lists and their usage situations? Let’s find out</p><h3>List in Java</h3><p>List in Java, or interface java.util.List is described as a</p><ul><li>Ordered list</li><li>Elements can be retrieved anywhere in the list</li></ul><p>The two most common classes that implement List are <strong>ArrayList </strong>and <strong>LinkedList </strong>(common by discussions, not usages. I’m talking about <strong>LinkedList</strong>)</p><h3>ArrayList</h3><p>The advantages of arrays are memory saving and fast random access speed (getting an element at any index). However, in return, arrays must have a fixed length when you initialize. If you declare too large, it will consume memory, too small is not enough to store.<br>To facilitate both use and access speed, <strong>ArrayList </strong>was born to overcome those disadvantages but still inherit the advantages of array’s data retrieval.<br><strong>ArrayList</strong> does that by using a <a href="https://en.wikipedia.org/wiki/Dynamic_array">dynamic array</a> to store elements. <strong>ArrayList </strong>just calculates to create a new array of appropriate size and copies all elements from the old array to the new array to add or just shift the elements to delete.<br>The array of a <strong>ArrayList </strong>starts being empty and has an integer variable that indicates that the actual size of the <strong>ArrayList</strong>, called size, is zero.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*xKZ2OijLJwS6SF9G.png" /></figure><p>This array is an empty static array and share for all <strong>ArrayList </strong>constructors to minimize memory usage if you have just initialized but not used. So no matter how many <strong>ArrayList</strong> you initiate, no more arrays will be created until you start using <strong>ArrayList</strong>.<br>When adds a new element, <strong>elementData</strong> will be assigned with a new array whose length is usually equal to 10.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*lTpJcAJU3FhaPdlc.png" /></figure><p>As you continue to add more elements, <strong>elementData </strong>will be filled</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*pNIs3FSkGaPWk0J0.png" /></figure><p>Assuming <strong>elementData </strong>has been full (10 elements)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*qNtIiDtziRf5bVJZ.png" /></figure><p>When we continuous add more elements, <strong>elementData </strong>will again be initialized with a new array has size is increased by 50% of the original size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*aXVvtzPwC3y18Hjp.png" /></figure><p>In the case of delete, assuming delete at index 5, perform:</p><ul><li>Copy the item from position 5 + 1 to the end and override index 5</li><li>The value in the last position will be redundant, setting the value to null</li><li>Reduce the size of the list by 1</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*ZY1Z4MnTIt7afnp4.png" /></figure><p>Now we have a list of only 10 elements, but the size of the array stays at 15 slots<br><strong>Comments</strong>:</p><ul><li>By constantly creating new arrays and copying arrays, <strong>ArrayList </strong>will be poor at adding or deleting elements, which will get worse as the number of elements increases.</li><li>Random access in <strong>ArrayList </strong>is indexed access in array, so the speed is very fast.</li><li>Deletion of <strong>ArrayList </strong>will work poorly if you delete with small indexes, the worst will be index = 0. Let’s say your list size = 100. If you delete the first element, the ArrayList will have to copy 99 elements.</li><li>The array in <strong>ArrayList </strong>will get bigger and bigger as you add elements, adding 50% at a time when there is no save space, and not diminishing when you delete. You can use a method of <strong>ArrayList </strong>called <strong>trimToSize </strong>to remove redundant array slots</li></ul><h3>LinkedList</h3><p><strong>LinkedList </strong>is a <a href="https://en.wikipedia.org/wiki/Linked_list#Doubly_linked_list">doubly-linked list</a>, instead of using an array to store data like <strong>ArrayList</strong>, <strong>LinkedList </strong>uses a linked list structure.<br>This is wow it works:</p><ul><li>Has a size variable to store the actual size of the list, like <strong>ArrayList</strong></li><li>An property called Node <strong>first </strong>to store the first element of the list. Originally not there will be null</li><li>Another property called Node <strong>last </strong>to store the last element of the list. Originally not there will be null</li><li>Each node will contain 3 properties: the node’s actual data (called item), its next node (called <em>next)</em>, and a node immediately before it (called <em>prev)</em></li></ul><p>Initially, <strong>LinkedList </strong>will have 2 nodes: <strong>first </strong>and <strong>last </strong>nodes, both null</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*eayOdX44RKP_uWNU1Dq5xw.png" /></figure><p>When adding the first element, link the <strong>first </strong>node to that element</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*2cjCkke1RXM8531gPxsSTw.png" /></figure><p>When adding the next element, link the <strong>last </strong>node to it and create two-side link between the <strong>first </strong>node and the <strong>last </strong>node. Now the list has at least 2 nodes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*nAStFlDijImwEWzKPorGAA.png" /></figure><p>Just like that, when continuing to insert, whether at the bottom of the list or at the top of the list, the <strong>LinkedList </strong>just links the nodes together</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*KIYC5_tNCpiZN1HS.png" /></figure><p>Similarly, when adding in the middle of the list, the list also simply creates a new node, changes the association of 2 nodes next to the newly added node</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*rFeeWghSWC0oLO3p.png" /></figure><p>When deleting, <strong>LinkedList </strong>also changes the link of 2 nodes next to the node that was just deleted</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*DWfkq3Z-5-3CjPen.png" /></figure><p>When you need to retrieve an element in any index, unlike <strong>ArrayList</strong>, <strong>LinkedList </strong>must go node by node from first or last depending on which index is nearby.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*ex2G7YXk6S2kDXgK.png" /></figure><p>Let’s say you have a list with 1000 elements. When you need to retrieve an element with index = 500, <strong>LinkedList </strong>will have to browse all 500 elements to get the one you want, which is very bad.</p><p><strong>Comments</strong>:</p><ul><li><strong>LinkedList’</strong>s randomly placed element finding is worse than <strong>ArrayList</strong>, especially with the index in the center</li><li>Adding or removing nodes in the <strong>LinkedList </strong>is easy, but it gets worse if you insert/delete as much as possible to the center of the list.</li></ul><h3>ArrayList vs LinkedList</h3><p>From the comments above, you can completely draw a comparison between <strong>ArrayList</strong> and <strong>LinkedList</strong>.<br>Personally, I have never used <strong>LinkedList</strong>, for the following reasons:</p><h4>We all use small or medium sized lists.</h4><p>When the list is small, the expansion speed of the dynamic array is not inferior to that of <strong>LinkedList</strong>.<br>Below is a benchmark of insertion speeds with different sizes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*529YbtUyh01tm82N.png" /></figure><p>Not too much difference</p><h4>We tend to use lists for browsing and searching more than inserting elements one by one.</h4><p>Browsing with an array is definitely superior to browsing through each element of the <strong>LinkedList</strong></p><h3>There are many ways to create a ArrayList containing multiple elements while still overcoming the disadvantages of ArrayList</h3><ul><li>Create ArrayList from other collections: new ArrayList&lt;&gt;(Collection&lt;&gt; e);</li><li>Add multiple elements at once using list.addAll(Collection&lt;&gt; e);</li><li>Init the right capacity: new ArrayList&lt;&gt;(int initialCapacity)</li><li>Use the Stream API. Stream API using list.addAll</li></ul><h4>LinkedList takes a lot of memory to store</h4><p>Suppose there is a list of integers, with size = 1000, and size = 1000_000, the space required for storage is as follows:</p><p>The calculation of an <strong>ArrayList </strong>when adding 1000 values will be (not count the data):</p><ul><li>object reference = 8</li><li>size = 4</li><li>elementData reference = 8</li><li>elementData object = 12</li><li>elementData reference items = 8 * 1000 = 8000 bytes</li></ul><p>Total 8032 bytes</p><p>Even in worse case when <strong>ArrayList </strong>has maximum unused array slots, it only 8 + 4 + 8 + 12 + 8 * 1500 = 12032 bytes<br>With <strong>LinkedList</strong>:</p><ul><li>size = 4</li><li>Node first reference = 8</li><li>Node last reference = 8</li><li>Each node size = 8 (item reference) + 8 (next reference) + 8 (prev reference) = 24. All node will equal node size * 1000 = 24000</li></ul><p>Total 24020 bytes</p><p>You can see that <strong>LinkedList </strong>takes 2–3 times as much space as <strong>ArrayList</strong>.</p><p>In addition, <strong>arrays </strong>are always more garbage collection friendly than <strong>LinkedList</strong>. <strong>arrays </strong>can store as many as it wants (of course, not large than max of integer), so <strong>ArrayList </strong>only need to create one object (an array) to store anything. In the other hand, <strong>LinkedList </strong>has to create the number of objects equal to the size of list. If you need a list to store one million items, LinkedList creates one million objects but <strong>ArrayList </strong>only need one.</p><h4>LinkedList insert/delete is good, but not fast as you think.</h4><p>Let’s say you need to insert or delete in the middle of the list. Before it can insert/delete, it has to browse through half of the list elements, which <strong>LinkedList </strong>does so bad</p><h4>So where are exactly LinkedList good?</h4><p>Well, in my opinion, <strong>LinkedList </strong>is not good as a list at all. The only think it is better than <strong>ArrayList </strong>is queue, when you access from the first and last element intently. But then I realized that we do have <strong>ArrayDeque</strong> which is like <strong>ArrayList </strong>but “<em>faster than LinkedList when used as a queue</em>”. And that’s why I have never used <strong>LinkedList</strong>.</p><h3>Reference</h3><ul><li><a href="https://dzone.com/articles/java-object-size-estimation-measuring-verifying?source=post_page-----e2c831b36dc7--------------------------------">Java Object Size: Estimating, Measuring, and Verifying via Profiling - DZone</a></li><li><a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html?source=post_page-----e2c831b36dc7--------------------------------">ArrayList (Java Platform SE 8 )</a></li><li><a href="https://docs.oracle.com/javase/8/docs/api/java/util/LinkedList.html?source=post_page-----e2c831b36dc7--------------------------------">LinkedList (Java Platform SE 8 )</a></li></ul><p><em>Originally published at </em><a href="https://luanvv.com/blog/arraylist-va-linkedlist/"><em>https://luanvv.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fbaf46ddc350" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sử dụng Enum trong JPA]]></title>
            <link>https://luanvv.medium.com/s%E1%BB%AD-d%E1%BB%A5ng-enum-trong-jpa-3865a769597d?source=rss-168e44be4c62------2</link>
            <guid isPermaLink="false">https://medium.com/p/3865a769597d</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[enum]]></category>
            <category><![CDATA[jpa]]></category>
            <dc:creator><![CDATA[Luan Vu]]></dc:creator>
            <pubDate>Thu, 20 Jul 2023 02:11:38 GMT</pubDate>
            <atom:updated>2023-07-20T02:11:38.873Z</atom:updated>
            <content:encoded><![CDATA[<p>Enum luôn được khuyên dùng và được sử dụng rất phổ biến trong JPA. Enum giúp kiểm tra giá trị đầu vào của database, đồng thời thể hiện trực quan giá trị của database thông qua Enum ở tầng Java code. Cùng xem qua các cách khai báo Enum và những chú ý khi sử dụng chúng trong bài viết này</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Il3xxhjCe718OKvCmR85oA.png" /></figure><p>Có 2 cách chính sử dụng Enum trong JPA: <strong>@Enumerated</strong> và <strong>@Convert</strong></p><h4>@Enumerated</h4><pre>public enum Status {<br>    ACTIVE, DEACTIVATE;<br>}</pre><pre>@Entity<br>public class Admin {<br>  @Id<br>  private int id;<br>  private String name;<br><br>  @Enumerated<br>  private Status status;<br>}</pre><p>Mặc định <strong>Enumerated</strong> sẽ có EnumType là ORDINAL, lưu theo thứ tự khai báo của Enum và kiểu dữ liệu là Integer (hoặc NUMBER)</p><p>ACTIVE sẽ là 0, và DEACTIVATE sẽ là 1</p><pre>var admin = new Admin();<br>admin.setName(&quot;John&quot;);<br>admin.setStatus(Status.DEACTIVATE);</pre><pre>insert <br>into<br>    Admin<br>    (status, name, id) <br>values<br>    (?, ?, ?)<br>...<br>binding parameter [1] as [INTEGER] - [1]<br>binding parameter [2] as [VARCHAR] - [John]<br>binding parameter [3] as [INTEGER] - [1]</pre><p>ngược lại khi query</p><pre>select<br>        admin0_.id as id1_6_,<br>        admin0_.name as name2_6_,<br>        admin0_.status as status3_6_<br>    from<br>        admin admin0_ <br>...<br>extracted value ([id1_6_] : [INTEGER]) - [1]<br>extracted value ([name2_6_] : [VARCHAR]) - [John]<br>extracted value ([status3_6_] : [INTEGER]) - [DEACTIVATE]</pre><p>Nếu để EnumType là <em>STRING</em>, giá trị trong database sẽ là tên của Enum và kiểu dữ liệu là text (hoặc VARCHAR)</p><pre>@Entity<br>public class Admin {<br>  @Id<br>  private int id;<br>  private String name;<br><br>  @Enumerated(EnumType.STRING)<br>  private Status status;<br>}</pre><pre>insert <br>into<br>    Admin<br>    (status, name, id) <br>values<br>    (?, ?, ?)<br>...<br>binding parameter [1] as [INTEGER] - [1]<br>binding parameter [2] as [VARCHAR] - [John]<br>binding parameter [3] as [VARCHAR] - [DEACTIVATE]</pre><h4>@Convert</h4><p>Cách này yêu cầu viết thêm một Converter class như dưới đây</p><pre>@Converter(autoApply = true)<br>public class StatusConverter implements AttributeConverter&lt;Status, Integer&gt; {<br><br> public Integer convertToDatabaseColumn(Status value) {<br>  if (value == null) {<br>   return null;<br>  }<br>  return value.getValue();<br> }<br><br> public Status convertToEntityAttribute(Integer value) {<br>  if (value == null) {<br>   // Can throw an exception here<br>   return null;<br>  }<br>  return Status.fromValue(value);<br> }<br>}</pre><pre>@Entity<br>public class Admin {<br>  @Id<br>  private int id;<br>  private String name;<br><br>  @Convert(converter = StatusConverter.class)<br>  private Status status;<br>}</pre><p>Annotation @Convert ở entity có thể bỏ do ta đã khai báo <em>@Converter(autoApply = true)</em></p><p>Với cả 2 cách trên, khi thêm data vào database, chỉ thao tác với Enum thuần túy, không cần quan tâm giá trị thực trong database</p><pre>var admin = new Admin();<br>...<br>admin.setStatus(Status.ACTIVE);</pre><p>Khi query</p><pre>List&lt;Admin&gt; findByStatus(Status status);<br><br>@Query(&quot;FROM Admin WHERE status = ?1&quot;)<br>List&lt;Admin&gt; listAllByStatus(Status status);</pre><p>Với JPQL hay HQL, một khi đã sử dụng kiểu Enum, ta sẽ bắt buộc sử dụng Enum trong tham số, không thể dùng giá trị thực trong database.</p><p>Không thể viết</p><pre>@Query(&quot;FROM Admin WHERE status = 0&quot;)<br>List&lt;Admin&gt; listAllActiveStatus();<br><br>@Query(&quot;FROM Admin WHERE status = ?1&quot;)<br>List&lt;Admin&gt; listAllByStatus(String status); // Kiểu của status phải là Enum</pre><p>Ngoài ra, bạn có thể sử dụng Custom Type. Tuy nhiên cách này phức tạp hơn và thừa thãi nếu chỉ dùng để mapping Enum. Có thể tham khảo thêm <a href="https://docs.jboss.org/hibernate/orm/current/userguide/html_single/Hibernate_User_Guide.html#basic-enums-custom-type">tại đây</a></p><h4>Đánh giá các cách dùng Enum</h4><ul><li>Sử dụng Enumerated ORDINAL có vẻ ổn, nhưng sẽ phát sinh lỗi không ngờ tới nếu bạn thay đổi thứ tự của Enum</li></ul><pre>public enum Status {<br>    ACTIVE, BLOCKED, DEACTIVATE;<br>}</pre><p>Lúc này nếu status trong database là 1 sẽ trả về <strong>BLOCKED</strong> chứ không còn là <strong>DEACTIVATE </strong>như cũ</p><pre>select<br>        admin0_.id as id1_6_,<br>        admin0_.name as name2_6_,<br>        admin0_.status as status3_6_<br>    from<br>        admin admin0_ <br>...<br>extracted value ([id1_6_] : [INTEGER]) - [1]<br>extracted value ([name2_6_] : [VARCHAR]) - [John]<br>extracted value ([status3_6_] : [INTEGER]) - [BLOCKED]</pre><ul><li>Tương tự thì với Enumerated STRING, lỗi sẽ phát sinh nếu bạn thay đổi tên các phần tử của Enum.</li><li>Dùng @Convert an toàn nhưng lại yêu cầu viết thêm class Converter</li></ul><h4>Nên sử dụng Enum như thế nào?</h4><p>Trong gần 10 năm qua, mình luôn luôn sử dụng kiểu số trong database sau đó mapping với JPA bằng @Convert, vì cho rằng điều đó sẽ giúp tối ưu lưu trữ trong database. Nhưng hóa ra, điều đó là không cần thiết và rất bất tiện.</p><p>Giả sử bạn sử dụng kiểu số. Dù bạn chính là người viết ra những Enum đó, thì cũng sẽ cũng lúc bạn tự hỏi những status 1, 2, 3, 4 trong database là gì. Kết quả là bạn lại phải quay lại code để xem trong Enum. Ngoài lập trình viên, nhiều role khác cũng sẽ có nhu cầu truy vấn database. Bạn sẽ lại phải giải thích cho họ status 1, 2, 3, 4 trong database có nghĩa là gì. Ngoài ra, dữ liệu khi được trích xuất và sử dụng ở những ứng dụng khác, Enum trở lên vô dụng ở đó và lại cần phải xây dựng một converter riêng.</p><p>Thay vào đó, nếu trong database hiển thị luôn ACTIVE, BLOCKED, DEACTIVATE, sẽ chẳng cần bạn hoặc bất kỳ ai giải thích gì thêm. Việc trao đổi giữa các hệ thống cũng trở nên vô cùng đơn giản vì nó đã quá rõ ràng rồi.</p><p>Vấn đề tối ưu dữ liệu cũng không cần quá nghiêm trọng hóa. Bạn chỉ tốn thêm vài byte mỗi record để lưu kiểu chữ thay vì số. Quá nhỏ so với những lợi ích nó mang lại.</p><p>Do đó, mình khuyến nghị sử dụng Enumerated STRING. Vừa trực quan lại dễ dàng khai báo vì không yêu cầu viết thêm bất kỳ converter nào khác.</p><h4>Reference</h4><ul><li><a href="https://vladmihalcea.com/the-best-way-to-map-an-enum-type-with-jpa-and-hibernate/">The best way to map an Enum Type with JPA and Hibernate</a></li><li><a href="https://docs.jboss.org/hibernate/orm/current/userguide/html_single/Hibernate_User_Guide.html#basic-enums">Hibernate ORM 6.2.6.Final User Guide</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3865a769597d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Chúng ta đang viết SQL LIKE sai cách]]></title>
            <link>https://luanvv.medium.com/ch%C3%BAng-ta-%C4%91ang-vi%E1%BA%BFt-sql-like-sai-c%C3%A1ch-b91110975410?source=rss-168e44be4c62------2</link>
            <guid isPermaLink="false">https://medium.com/p/b91110975410</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring]]></category>
            <dc:creator><![CDATA[Luan Vu]]></dc:creator>
            <pubDate>Fri, 16 Dec 2022 17:27:53 GMT</pubDate>
            <atom:updated>2023-01-09T04:55:20.337Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*BxAX4D_0qTz5tNV0xkwX-g.jpeg" /></figure><p>Nhiều người luôn nghĩ và viết câu SQL Like khá là đơn giản: <strong>WHERE title LIKE ‘%abcxyz%’</strong>. Sự thật là viết như vậy là sai và rất dễ dẫn đến lỗi. Cùng xem bài viết dưới đây để tìm hiểu</p><p>Giả sử ta có một bảng Voucher như sau:</p><pre>+────────+──────────────────────────────────────────+<br>| ID     | Title                                   |<br>+────────+──────────────────────────────────────────+<br>| 1      | Udemy 80% Discount + Extra 15% Off       |<br>+────────+──────────────────────────────────────────+<br>| 2      | Udemy $15.99 Off                         |<br>+────────+──────────────────────────────────────────+<br>| 3      | Udemy Coupon | $80 + Extra 55% Discount  |<br>+────────+──────────────────────────────────────────+</pre><p>Sử dụng một câu SQL Like đơn giản như dưới đây</p><pre>SELECT id, title FROM voucher WHERE title LIKE %?%</pre><p>Thử với một số từ khóa thay thế vào dấu hỏi (?)</p><pre>+──────────+──────────────────────────────────────────+<br>| Keyword  | Result                                   |<br>+──────────+──────────────────────────────────────────+<br>| Udemy    | Udemy 80% Discount + Extra 15% Off       |<br>|          | Udemy $15.99 Off                         |<br>|          | Udemy Coupon | $80 + Extra 55% Discount  |<br>+──────────+──────────────────────────────────────────+<br>| 80       | Udemy 80% Discount + Extra 15% Off       |<br>|          | Udemy Coupon | $80 + Extra 55% Discount  |<br>+──────────+──────────────────────────────────────────+<br>| Discount | Udemy 80% Discount + Extra 15% Off       |<br>|          | Udemy Coupon | $80 + Extra 55% Discount  |<br>+──────────+──────────────────────────────────────────+<br>| 15%      | Udemy 80% Discount + Extra 15% Off       |<br>|          | Udemy $15.99 Off                         |<br>+──────────+──────────────────────────────────────────+<br>| %        | Udemy 80% Discount + Extra 15% Off       |<br>|          | Udemy $15.99 Off                         |<br>|          | Udemy Coupon | $80 + Extra 55% Discount  |<br>+──────────+──────────────────────────────────────────+<br>| _        | Udemy 80% Discount + Extra 15% Off       |<br>|          | Udemy $15.99 Off                         |<br>|          | Udemy Coupon | $80 + Extra 55% Discount  |<br>+──────────+──────────────────────────────────────────+</pre><p>Ba từ khóa cuối ra kết quả không đúng như mong đợi. Đó là vì trong keyword của ta có ký tự ‘%’ và ‘_’, có nghĩa là bất kỳ giá trị nào cũng được.</p><p>Để tránh lỗi, cách đơn giản là escape những ký tự đặc biệt đó trước khi truyền vào câu lệnh SQL. Ký tự dùng để escape thông thường là backslash (‘\’).</p><p>Lúc này kết quả sẽ ra đúng.</p><pre>+───────────────────+─────────────────+──────────────────────────────────────────+<br>| Original Keyword  | Escaped Keyword | Result                                   |<br>+───────────────────+─────────────────+──────────────────────────────────────────+<br>| 15%               | 15\%            | Udemy 80% Discount + Extra 15% Off       |<br>+───────────────────+─────────────────+──────────────────────────────────────────+<br>| %                 | \%              | Udemy 80% Discount + Extra 15% Off       |<br>|                   |                 | Udemy Coupon | $80 + Extra 55% Discount  |<br>+───────────────────+─────────────────+──────────────────────────────────────────+<br>| _                 | \_              |                                          |<br>+───────────────────+─────────────────+──────────────────────────────────────────+</pre><p>Ký tự escape thông thường là backslash (‘\’) nhưng cũng có thể tùy thuộc vào loại database bạn sử dụng. Lúc này SQL có thêm câu lệnh ESCAPE để bạn có thể chỉ định ký tự escape tùy sở thích.</p><pre>SELECT id, title FROM voucher WHERE title LIKE %15|%% ESCAPE &#39;|&#39;</pre><p>Đối với Spring Data, mọi thứ còn đơn giản hơn nhiều, bạn không cần phải escape input trước. Đoạn lệnh trên có thể được thay thế bằng <a href="https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.query-methods">Query Methods</a></p><pre>List&lt;Voucher&gt; findByTitleContains(String title);</pre><p>Câu lệnh SQL sinh ra sẽ là</p><pre>select voucher0_.id as id1_0_, voucher0_.title as title2_0_ <br>  from voucher voucher0_ where voucher0_.title like ? escape ?</pre><p>Parameter 1 là ‘%\_%’</p><p>Parameter 2 là ‘\’</p><p>Với JPQL, bạn cũng chỉ cần viết câu lệnh như sau</p><pre>@Query(&quot;FROM Voucher WHERE title LIKE %?#{escape([0])}% escape ?#{escapeCharacter()}&quot;)<br>List&lt;Voucher&gt; findByTitleContainsEscaped(String title);</pre><p>Tham khảo source code tại <a href="https://github.com/luanvuhlu/java-blog-sample/tree/master/like-query">Github</a></p><h3>Reference</h3><ul><li><a href="https://docs.spring.io/spring-data/jpa/docs/current/reference/html/">https://docs.spring.io/spring-data/jpa/docs/current/reference/html/</a></li><li><a href="https://dev.mysql.com/doc/refman/8.0/en/string-comparison-functions.html">https://dev.mysql.com/doc/refman/8.0/en/string-comparison-functions.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b91110975410" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ArrayList và LinkedList trong Java]]></title>
            <link>https://luanvv.medium.com/arraylist-v%C3%A0-linkedlist-trong-java-e2c831b36dc7?source=rss-168e44be4c62------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2c831b36dc7</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[arraylist-vs-linkedlist]]></category>
            <category><![CDATA[lists]]></category>
            <dc:creator><![CDATA[Luan Vu]]></dc:creator>
            <pubDate>Sat, 23 Apr 2022 09:26:18 GMT</pubDate>
            <atom:updated>2022-04-23T09:40:30.611Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*zvbzbupbfRUQB2tYPesOmw.png" /></figure><p>List là một collection được sử dụng rất phổ biến trong Java, đặc biệt là ArrayList và LinkedList. Đã bao giờ bạn tự hỏi sự khác nhau giữa hai list này và các tình huống sử dụng của chúng. Cùng tìm hiểu dưới đây.</p><h3>List trong Java</h3><p>List trong Java, hay interface java.util.List được mô tả như là một</p><ul><li>Danh sách có thứ tự</li><li>Có thể truy xuất phần tử ở một vị trí bất kỳ trong list</li></ul><h3>ArrayList</h3><p>Ưu điểm của array là tiết kiệm bộ nhớ và tốc độ truy xuất ngẫu nhiên (tìm một phần tử ở vị trí bất kỳ) nhanh. Tuy nhiên, đổi lại thì array phải có độ dài cố định khi bạn khởi tạo. Nếu khai báo nhiều quá sẽ tốn bộ nhớ, ít quá thì không đủ để lưu trữ.<br> Để thuận tiện cho cả việc sử dụng và tốc độ truy xuất, ArrayList ra đời để khắc phục các nhược điểm đó nhưng vẫn kế thừa ưu điểm trong việc truy xuất dữ liệu của array.<br> ArrayList làm điều đó bằng cách sử dụng một <a href="https://en.wikipedia.org/wiki/Dynamic_array">dynamic array</a> để lưu trữ các phần tử. Khi bạn thêm hoặc xóa phần tử, ArrayList sẽ tính toán để tạo một array mới có kích thước phù hợp và copy toàn bộ phần tử từ array cũ sang array mới.<br> Khởi điểm array sẽ rỗng và có một biến integer cho biết kích thước thực của ArrayList, gọi là size, bằng 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/0*hFluFf3Wt6KcvQZz.png" /></figure><p>Array này là một static array rỗng và share cho tất cả các hàm khởi tạo ArrayList để giảm thiểu bộ nhớ sử dụng nếu bạn mới chỉ khởi tạo chứ chưa dùng.<br> Khi bắt đầu thêm mới một phần tử, elementData sẽ được gán bằng một mảng mới có độ dài thường là bằng 10.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/0*Y_qx_qer2d25EvVa.png" /></figure><p>Khi tiếp tục thêm phần tử, elementData sẽ được lấp đầy</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/0*iOIhAVALLN9sJoYu.png" /></figure><p>Giả sử elementData đã được lấp đầy (10 phần tử)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/0*ttLsiUEnuCe7qTA0.png" /></figure><p>Khi ta lại thêm phần tử, elementData sẽ lại được khởi tạo bằng một array mới có size tăng thêm 50% size gốc</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/0*cX8RR6v5BZE6ZJ3B.png" /></figure><p>Cách thức tăng của elementData là newSize = oldSize * 1.5<br> Tương tự:<br> 10 -&gt; 15<br> 15 -&gt; 22<br> 22 -&gt; 33<br> 33 -&gt; 49<br> 49 -&gt; 73</p><p>Trong trường hợp delete, giả sử delete tại index 5, thực hiện:</p><ul><li>Copy item từ vị trí 5 + 1 tới cuối và đè vào index 5</li><li>Giá trị ở vị trí cuối sẽ bị thừa ra, đặt giá trị thành null</li><li>Giảm size của list đi 1</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/0*b_x9oTNXpV9ustjH.png" /></figure><p>Giờ ta có một list chỉ còn 10 phần tử.<br><strong>Nhận xét</strong>:</p><ul><li>Với cách liên tục tạo mới array và copy array, ArrayList sẽ kém trong việc thêm mới hoặc xóa phần tử, sẽ ngày một tệ hơn khi số phần tử tăng lên.</li><li>Truy xuất ngẫu nhiên trong ArrayList chính là truy xuất theo index trong array nên tốc độ rất nhanh.</li><li>Cách delete của ArrayList sẽ hoạt động kém nếu bạn delete với những index nhỏ, tệ nhất sẽ là index = 0. Giả sử list của bạn có size = 100. Nếu bạn delete phần tử đầu tiên, ArrayList sẽ phải copy 99 phần tử.</li><li>array trong ArrayList sẽ ngày một to ra khi bạn thêm phần tử, thêm mỗi lần 50% khi thiếu chỗ lưu và sẽ không giảm đi khi bạn delete.</li></ul><h3>LinkedList</h3><p>LinkedList là một danh sách liên kết kép ( <a href="https://en.wikipedia.org/wiki/Linked_list#Doubly_linked_list">Doubly-linked list</a>), thay vì dùng array để lưu dữ liệu như ArrayList, LinkedList lại dùng cấu trúc danh sách liên kết để lưu trữ.<br> Cách thức hoạt động như sau:<br> LinkedList bao gồm:</p><ul><li>size để lưu dung lượng thực của list, giống ArrayList</li><li>Node first để lưu phần tử đầu tiên của list. Ban đầu chưa có sẽ là null</li><li>Node last để lưu phần tử cuối cùng của list. Ban đầu chưa có sẽ là null</li><li>Mỗi node sẽ chứa data thực của node, gọi là item, một node kế tiếp của nó, gọi là next và một node đứng ngay trước nó, gọi là prev</li></ul><p>Khởi điểm, LinkedList sẽ bao gồm 2 node first và last đều mang giá trị null</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*MHinWjTqEbmSrF1P.png" /></figure><p>Khi thêm phần tử đầu tiên, thay thế node first bằng phần tử đó</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/0*mJ2j8bmN5285WzRx.png" /></figure><p>Khi thêm phần tử tiếp theo, thay vào node last và liên kết giữa node first và node last. Nay list đã có tối thiểu 2 node</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/0*FMUCYUGcpcNN_AWp.png" /></figure><p>Cứ như vậy, khi tiếp tục insert, dù là ở cuối danh sách hay đầu danh sách, LinkedList chỉ việc liên kết các node lại với nhau</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/0*b9tbbhbdMagoslAi.png" /></figure><p>Tương tự khi thêm ở giữa list thì list cũng chỉ cần đơn giản là tạo ra node mới, thay đổi liên kết 2 node bên cạnh node mới thêm vào</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/0*mjKQFpGq7z3BiWBX.png" /></figure><p>Tương tự như vậy, khi cần delete, LinkedList cũng thay đổi liên kết 2 node bên cạnh node vừa bị xóa</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/0*z3SA3dYqK4d3zLKi.png" /></figure><p>Khi cần lấy ra một phần tử ở index bất kỳ, không như ArrayList, LinkedList phải đi dần dần từng node một từ first hay last phụ thuộc vào index ở gần bên nào hơn.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/0*9RiPhbrtyQgCO8vq.png" /></figure><p>Giả sử bạn có một list với 1000 phần tử. Khi bạn cần lấy ra phần tử có index = 500, LinkedList sẽ phải duyệt tới toàn bộ 500 phần tử để có thể lấy ra cái bạn muốn, điều đó là rất tệ.</p><p><strong>Nhận xét</strong>:</p><ul><li>Việc tìm phần tử ở vị trí ngẫu nhiên của LinkedList kém hơn ArrayList, đặc biệt với index ở trung tâm</li><li>Việc thêm hoặc xóa node trong LinkedList rất dễ dàng nhưng sẽ tệ dần nếu bạn insert/delete càng về trung tâm của list.</li></ul><h3>ArrayList vs LinkedList</h3><p>Từ những nhận xét ở trên, các bạn hoàn toàn có thể rút ra so sánh giữa ArrayList và LinkedList.<br> Cá nhân mình, chưa bao giờ dùng LinkedList, vì các lý do sau:</p><h4>1. Chúng ta đều sử dụng những list có kích thước nhỏ.</h4><p>Khi list có kích thước nhỏ thì tốc độ mở rộng của dynamic array không hề thua kém so với LinkedList.<br> Dưới đây là benchmark tốc độ insert với các kích thước khác nhau.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IvjkTPhNEd3YL3dKpC2UDg.png" /></figure><p>Không có quá nhiều khác biệt</p><h4>2. Chúng ta có xu hướng sử dụng list để duyệt và tìm kiếm nhiều hơn so với insert từng phần tử một.</h4><p>Việc duyệt bằng array chắc chắn là vượt trội hơn so với cách duyệt qua từng phần tử của LinkedList</p><h4>3. Có nhiều cách để tạo ra 1 ArrayList chứa nhiều phần tử mà vẫn khắc phục được nhược điểm của ArrayList</h4><ul><li>Tạo ArrayList từ Collection khác: new ArrayList&lt;&gt;(Collection&lt;&gt; e);</li><li>Thêm nhiều phần tử một lúc bằng list.addAll(Collection&lt;&gt; e);</li><li>Định số phần tử trước khi insert: new ArrayList&lt;&gt;(int initialCapacity)</li><li>Dùng Stream API (Stream API sử dụng list.addAll)</li></ul><h4>4. LinkedList tốn nhiều bộ nhớ để lưu trữ</h4><p>Giả sử có một list các integer, với size = 1000, và size = 1000_000, dung lượng cần để lưu trữ như sau:</p><p>Cách tính một ArrayList khi add lần lượt 1000 integer sẽ bao gồm:</p><ul><li>object header = 12</li><li>size = 4</li><li>modCount = 4</li><li>elementData reference = 4</li><li>elementData header = 12</li><li>elementData size = 4</li><li>elementData item = 16 * 1234</li></ul><p>Total 19784 byte<br> Với LinkedList:</p><ul><li>object header = 12</li><li>size = 4</li><li>modCount = 4</li><li>Node first reference = 4</li><li>Node last reference = 4</li><li>Object alignment gap = 4</li><li>Node size = 12 (object header) + 4 (item reference) + 16 (Integer) + 4 (next reference) + 4 (prev reference) = 40</li><li>All node= node size * 1000 = 40000</li></ul><p>Total 40032 byte</p><p>Bạn có thể thấy là LinkedList tốn dung lượng gấp đôi so với ArrayList. Ngoài ra array luôn thân thiện với Garbage Collection hơn so với các Node của LinkedList.</p><h4>5. LinkedList insert/delete tốt nhưng chưa chắc đã nhanh.</h4><p>Giả sử bạn cần insert hoặc delete ở giữa list. Trước khi có thể insert/delete, nó phải duyệt qua một nửa số phần tử của list, điều mà LinkedList làm tệ nhất</p><h3>Một số mẹo khi dùng với list</h3><h3>findFirst hay findAny</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/0*Y4Vcyd4uC7DOFaRB.png" /></figure><p>Có người thích dùng findFirst, có người lại findAny, cái nào đúng hơn?<br> Với <a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/BaseStream.html#sequential--">sequential stream</a> và List trong Java là một list có thứ tự thì findFirst hay findAny cho ra kết quả như nhau và tốc độ như nhau trong mọi trường hợp.<br> Nhưng đối với parallel stream, findAny có thể trả ra kết quả khác với findFirst. Hoặc bạn dùng nó với Set thì 2 hàm cũng cho ra kết quả khác nhau.</p><h4>Tìm kiếm một phần tử trong list</h4><p>Trước Java 8, tôi thường code như dưới đây</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/0*dh4SZCm0g4fL8vES.png" /></figure><p>Nhưng đến nay, hãy code như sau:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/0*YpfXanW7GvkwdDOf.png" /></figure><p>Không if-else, không for-loop</p><h4>Kiểm tra tất cả phần tử thỏa mãn điều kiện</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/0*1T8c7AgXlPmU7FN1.png" /></figure><h4>Kiểm tra có ít nhất một phần tử thỏa mãn điều kiện</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/0*YbQ3Mv6yFAGKLZsR.png" /></figure><h4>Sort list theo một field</h4><p>Sort theo ascending</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/0*wy0uf_0c46I8jsJ1.png" /></figure><p>Sort theo descending</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/0*F32Dcvzs7q-w_N8f.png" /></figure><h4>Delete các phần tử thỏa mãn điều kiện với removeIf</h4><p>Gọn hơn so với cách dùng iterator.remove.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/0*cb3mX3aFxM_2BGlf.png" /></figure><h3>Reference</h3><ul><li><a href="https://dzone.com/articles/java-object-size-estimation-measuring-verifying">Java Object Size: Estimating, Measuring, and Verifying via Profiling - DZone Java</a></li><li><a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html">ArrayList (Java Platform SE 8 )</a></li><li><a href="https://docs.oracle.com/javase/8/docs/api/java/util/LinkedList.html">LinkedList (Java Platform SE 8 )</a></li></ul><p><em>Originally published at </em><a href="https://luanvv.com/blog/arraylist-va-linkedlist/"><em>https://luanvv.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2c831b36dc7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Data JPA/Hibernate Tips: chỉ nên lấy ra thứ bạn cần]]></title>
            <link>https://luanvv.medium.com/spring-data-jpa-hibernate-tips-ch%E1%BB%89-n%C3%AAn-l%E1%BA%A5y-ra-th%E1%BB%A9-b%E1%BA%A1n-c%E1%BA%A7n-da4cd3b64da4?source=rss-168e44be4c62------2</link>
            <guid isPermaLink="false">https://medium.com/p/da4cd3b64da4</guid>
            <category><![CDATA[hibernate]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[tips-and-tricks]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[jpa]]></category>
            <dc:creator><![CDATA[Luan Vu]]></dc:creator>
            <pubDate>Sun, 26 Dec 2021 07:20:58 GMT</pubDate>
            <atom:updated>2021-12-26T07:20:58.809Z</atom:updated>
            <content:encoded><![CDATA[<p>Trong JPA/Hibernate, nếu bạn không chỉ định field thì sẽ được coi là bọn sẽ lấy ra mọi trường. Nếu bạn chỉ định fetch EAGER thì sẽ thêm phần JOIN hoặc thêm câu lệnh SELECT và đương nhiên sẽ lấy ra mọi trường của bảng liên quan nếu bạn không chỉ định. Và đó, chính là nguyên nhân gây chậm hệ thống</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QMeNA63OjfVQQad_" /></figure><h3>Select column có chọn lọc</h3><p>Giả sử ta có bảng BOOK với 12 field. Nếu chúng ta lấy ra entity Book (map to bảng BOOK) bằng một số cách như dưới đây</p><pre>CrudRepository.findAll();</pre><pre>CrudRepository.findById(ID id);</pre><pre>@Query(“FROM Book b”);</pre><p>thì Hibernate sẽ luôn lấy ra mọi field của entity Book, tức là 12 field như này:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/0*IJGsAD_s2B821L1w" /></figure><p>Việc lấy ra mọi field sẽ khiến bạn sử dụng dễ dàng hơn, cũng như Hibernate đưa entity vào persisten context, từ đó có khả năng quản lý trạng thái của entity. Tuy nhiên thì việc đó cũng phải đánh đổi bằng hiệu năng nếu chúng ta không cần tất cả những thông tin trên.</p><p>Giả sử ta chỉ cần lấy ra ID và TITLE, ta có thể viết như sau:</p><pre>@Query(&quot;SELECT new Book(id, title) FROM Book&quot;)<br>List&lt;Book&gt; findAllTitle();</pre><p>Khi đó, Hibernate chỉ sinh ra câu SQL đơn giản như sau:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/0*vMariHYbYvAJPhCr" /></figure><p>Điều hiển nhiên là nếu bạn lấy ra càng ít dữ liệu từ database thì vừa giảm tải cho database, vừa giảm thời gian lấy dữ liệu từ đó về. Tuy nhiên, nó cũng tạo thêm việc và giảm đi tính tiện dụng của JPA. Vậy nên trừ khi bạn có rất nhiều field và điều đó ảnh hưởng lớn đến hiệu năng của chương trình thì mới nên dùng.</p><h3>Luôn dùng fetchType là Lazy cho associations</h3><p>Association trong JPA được hiểu là cách liên kết giữa các entity với nhau.</p><p>fetchType cho các association được hiểu là khi bạn lấy ra một entity thì các association hoặc các field sẽ được lấy ra như thế nào</p><ul><li>EAGER: sẽ được lấy ra theo và bạn không thể thay đổi được nữa.</li><li>LAZY: sẽ không được lấy ra theo mà do ta quyết định tại thời điểm sử dụng.</li></ul><p>JPA có 3 loại associations, tương ứng với fetchType mặc định</p><ul><li>OneToMany, mặc định là FetchType.LAZY</li><li>ManyToOne, mặc định là FetchType.EAGER</li><li>OneToOne, mặc định là FetchType.EAGER</li></ul><p>Giả sử ta có 2 entity như sau:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/0*LOJ2iuVeo-gQj9iR" /></figure><p>Theo mặc định, association ManyToOne sẽ có FetchType là EAGER, OneToMany là LAZY</p><p>Nếu ta dùng cú pháp CrudRepository.findById(ID id), SQL sinh ra sẽ như sau:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*T-BdAHX-Q7BxckHJ" /></figure><p>Nếu ta dùng PagingAndSortingRepository.findAll(Pageable pageable), SQL sinh ra còn tệ hơn nữa, Hibernate sẽ sinh ra 3 câu SQL thay vì 2 dù chỉ lấy ra chỉ một record</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/0*R64QjfeDIDI-SGi_" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wANPDGJNF4utL1Er" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/0*mcQwAP8XqlHkB1x7" /></figure><p>Trường hợp này là do thay vì Join như trường hợp 1, Hibernate lại dùng một câu SQL riêng biệt để lấy ra Publisher. Vấn đề này liên quan đến FetchMode (SELECT thay vì JOIN) của Hibernate. Tham khảo <a href="https://www.baeldung.com/hibernate-fetchmode">FetchMode in Hibernate</a></p><p>Vậy là nếu dùng FetchType là EAGER, sẽ có 2 vấn đề xảy ra:</p><ul><li>SQL sinh ra luôn luôn lấy ra (thường là) nhiều hơn những gì ta cần. Không chỉ thêm field, join thêm bảng mà còn thêm cả số lượng SQL.</li><li>Bạn không thể ngăn cản điều trên</li></ul><p>Vì 2 lý do trên, tôi luôn luôn dùng FetchType.LAZY cho mọi association</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/0*r23X6RqqtPjko_kZ" /></figure><p>Khi này thì khi bạn select entity Book, entity Publisher sẽ không được lấy theo, điều đó tùy thuộc vào sự lựa chọn của bạn, ví dụ bạn có thể lấy ra bằng câu lệnh sau</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/0*T8Jn3GFDqB9M5esG" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zZWbuGKoJ3DLDOMU" /></figure><h3>Sử dụng lazy trên field khi có thể</h3><p>Không chỉ các association mới có FetchType, thật ra các field/column cũng có. Việc để các field là LAZY sẽ hữu ích nếu trong một entity, bạn có các field quá lớn: size của String quá lớn, lưu kiểu binary, blob, clob,… và không phải lúc nào cũng cần lấy ra.</p><p>Để sử dụng tính năng này, cần phải bât Bytecode enhancement. Hướng dẫn tại link dưới đây:</p><p><a href="http://the%20best%20way%20to%20lazy%20load%20entity%20attributes%20using%20jpa%20and%20hibernate/">The best way to lazy load entity attributes using JPA and Hibernate</a></p><p>Dưới đây là thông số thử nghiệm với các loại câu lệnh khác nhau</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*XFA6GwOZ6m8-bVgMx93jMw.png" /></figure><ul><li>All fields lazy: select all field của entity Book, tốn 546ms</li><li>Id and title: chỉ select id và tittle của Book, tốn 142ms</li><li>All fields Eager Select: select tất cả các field của Book và Publisher và dùng FetchMode.SELECT. Sinh ra 2294 câu SQL (vì có 2293 Publisher). Tốn 5334ms</li><li>All fields Eager Join: select tất cả các field của Book và Publisher và dùng FetchMode.JOIN. Chỉ sinh ra 1 câu lệnh SQL. Tốn 640ms</li><li>Id, title and publisher: select id, title của Book và publisher name. Chỉ sinh ra 1 câu lệnh SQL. Tốn 180ms</li></ul><p>Có thể thấy:</p><ul><li>Lấy ra toàn bộ các field lâu hơn 3.5x lần so với lấy ít field hơn</li><li>FetchMode.SELECT sẽ sinh ra n+1 câu SQL, với n là số lượng association entity có. Giả sử lấy ra 11000 book records, trong đó có 2293 publisher thì sẽ tốn 1 câu SQL để lấy ra 11000 book records và 2293 câu SQL để lấy ra toàn bộ publisher. Và hiển nhiên là càng nhiều câu SQL đồng nghĩa với xử lý nhiều hơn và lâu hơn.</li></ul><h3>Kết luận</h3><p>Hãy chú ý những điều sau khi mapping hoặc query trong Hi</p><ul><li>Luôn luôn mapping association với FetchType là LAZY trong mọi trường hợp.</li><li>Luôn chú ý FetchMode sử dụng là JOIN hay SELECT bằng cách xem SQL sinh ra</li><li>Nếu có thể, chỉ lấy ra các field cần thiết thay vì lấy ra toàn bộ các field của entity.</li><li>Nếu một entity có field với size quá lớn mà không phải lúc nào cũng cần, hãy thử chuyển FetchType của field sang LAZY.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da4cd3b64da4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 Books Every Java Developer Should Read]]></title>
            <link>https://luanvv.medium.com/5-books-every-java-developer-should-read-c3169a74c59b?source=rss-168e44be4c62------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3169a74c59b</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[books]]></category>
            <dc:creator><![CDATA[Luan Vu]]></dc:creator>
            <pubDate>Sun, 14 Nov 2021 16:13:08 GMT</pubDate>
            <atom:updated>2021-11-14T16:13:08.274Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I will give 5 books that I think everyone should read if they want to understand and work well with Java. Many of you who are learning about Java (or any technical knowledge) are going in the wrong direction. You go from the basic thing (Getting Started, <a href="http://www.tutorialspoint.com/">www.tutorialspoint.</a> com,…), sounds good. Then go straight to the real projects. You think practicing is the best way to learn, but after many years, you realize you’re standing still. Your knowledge is limited, you always think that what you know is 100% right and no need to learn more. But the knowledge out there is limitless and constantly changing. Some of you go around social networks, blogs or website, such as Facebook, Medium, Youtube, etc. and think that you are always updating your knowledge, but the truth is that you are walking around, not really learning deeply and fully, you are just fooling yourself. That’s why I always encourage people to read books. Spending a month reading books will obviously give you more knowledge than a year surfing Facebook (obviously everyone knows it is for playing, not learning). But why using Facebook to learn? Seriously!</p><p><em>Actually, some channels and videos on Youtube have excellent quality, but they are not fascinating for most of you guy. So you endup choosing more funny videos, but not helpful in my opinion.</em></p><h3><a href="https://www.amazon.com/dp/B083K3Q7QQ?ref_=dbs_s_ks_series_rwt">Core Java Volume I &amp; II</a> — Cay Horstmann</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/0*yjmqF3aoClKqNLSn.jpg" /></figure><p>The series provides complete knowledge of the Java language: the core Java components, common APIs and many useful tips &amp; tricks. The content of the series is extremely voluminous, with over 900 pages each, spanning most of the important Java content and Java versions (9, 10 and 11), each problem solved. There also is no shortage of useful sample code for your reference.</p><p>If you don’t know anything about Java then this series will be the best way to approach. And if you’re doing Java and think you understand Java, think again and read this series. You will find that there are many issues you do not fully understand and also many problems you do not know.</p><p>This set includes 2 books:<br><a href="https://www.amazon.com/Core-Java-I-Fundamentals-Cay-Horstmann-ebook-dp-B07G8DHTSZ/dp/B07G8DHTSZ/ref=mt_other?_encoding=UTF8&amp;me=&amp;qid=1603883127"><strong>Core Java, Volume I — Fundamentals (Core Series)</strong></a><br><a href="https://www.amazon.com/Core-Java-II-Advanced-Features-Horstmann-ebook-dp-B07NCXJR1M/dp/B07NCXJR1M/ref=mt_other?_encoding=UTF8&amp;me=&amp;qid=1603883127"><strong>Core Java, Volume II — Advanced Features (Core Series)</strong></a><br> If you want to work well with Java, I consider this a must-read book whether you are a senior or new in Java.</p><h3><a href="https://www.amazon.com/Effective-Java-Joshua-Bloch-ebook/dp/B078H61SCH/ref=sr_1_1?dchild=1&amp;keywords=Effective+Java&amp;qid=1603883394&amp;s=digital-text&amp;sr=1-1">Effective Java</a> — Bloch Joshua</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/0*oDG53ahw-J5tKtBO.jpg" /></figure><p>As the name suggests, this book will give you useful advice when using the Java language. With a huge amount of knowledge about Java, it will be difficult for you to notice the details and come up with effective ways to use it in the process of working with Java. Those things require a lot of research, experimentation and experience over a long period of time. Luckily you don’t have to do that, the author did it all and wrote in <strong>Effective Java</strong>. The book provides best practices, points out common misconceptions, and provides compelling proofs that even <strong>Oracle</strong> doesn’t tell you.</p><p>For example, do you know how to properly override <em>equals</em>, <em>hashCode</em>, <em>toString</em>, <em>clone</em> and why we need to do it. Or when to not use parallel streams, and many other good things.</p><p>The book will be divided into several chapters, each of which will include small passages mentioning a suggestion that I believe will surprise you with the suggestions.</p><h3><a href="https://www.amazon.com/Refactoring-Improving-Existing-Addison-Wesley-Signature-ebook-dp-B07LCM8RG2/dp/B07LCM8RG2/ref=mt_other?_encoding=UTF8&amp;me=&amp;qid=1573411753">Refactoring: Improving the Design of Existing Code</a> — Fowler Martin</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/0*ofM9pYcf5skU7pZS.jpg" /></figure><p>Many people when it comes to how to code (the art of code) so that it is beautiful, easy to understand, and easy to modify, they will immediately think of books like <a href="https://www.amazon.com/Clean-%20Code-Handbook-Software-Craftsmanship/dp/0132350882"><strong>Clean Code</strong></a>, <a href="https://www.amazon.com/Refactoring-Improving-Existing-Addison-Wesley-Signature-ebook-dp%20-B07LCM8RG2/dp/B07LCM8RG2/ref=mt_other?_encoding=UTF8&amp;me=&amp;qid=1573411753"><strong>The Art of Readable Code</strong></a>… But the books that impressed me the most were Refactoring, and the one above is one of them. Refactoring has a slightly different meaning than anything else. <strong>Design Patterns</strong>, <strong>SOLID</strong>, <strong>Clean Code</strong> will often follow the direction of design thinking, that is, as soon as you type the design key, you must immediately apply those philosophies, later it’s too late.</p><p>Why do I prefer Refactoring? Because it is easier to understand, remember and practical than the abstract thinking of <strong>Clean Code</strong> or the brain twisting of <strong>Design Patterns</strong>. Naming must be easy to understand, short and concise, but in practical application, not everyone can really do it right. Most of people I have interviewed know just one pattern, which is <strong>Singleton</strong>. Because the others are so confusing and with the style of just meeting deadlines, it is clear that <strong>Design Patterns</strong> is too far away.</p><p>Refactoring is extremely practical. When reviewing code, it throws to your face by a bunch of code with what people call Code Smells such as Long Method, Duplicate Code, Large Class, etc. and many other things that you don’t know the names of. From understanding how the code will be considered bad, you will know next time to avoid. And if you have missed it, you will know the Treatments. If the method is too long (Long Method), then separate the method (Extract Method), if the class is too large, separate the class (Extract Class), … and countless other Treatments.</p><p>I recommend this book to be read and practiced regularly to improve code quality.</p><p>If you don’t want to buy the book, there’s a lot of material on the internet on this, here’s an example: <a href="https://sourcemaking.com/refactoring">Refactoring (sourcemaking.com)</a></p><h3><a href="https://www.amazon.com/gp/product/B000SEIBB8/ref=ppx_yo_dt_b_d_asin_title_o01?ie=UTF8&amp;psc=1">Design Patterns: Elements of Reusable Object-Oriented Software</a> — Gamma Erich, Helm Richard, Johnson Ralph, Vlissides John</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*3aWjOcnTpMx6_6ey.jpg" /></figure><p>Perhaps it is not necessary to say much about how important Design Patterns is in object-oriented programming (OOP) today. Design Patterns is design patterns drawn from many years of OOP development, which make your code more flexible, easy to modify, extend and reuse. It offers 23 <strong>Design Patterns</strong>. Each pattern will start with a specific problem, the steps to analyze the problem, give the appropriate pattern, explain and finally the advantages and disadvantages of applying the pattern.</p><p>It is very useful for those of you who are in charge of design work, knowing <strong>Design Patterns</strong> is a huge advantage when applying for a job for anyone.</p><h3><a href="https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882">Clean Code: A Handbook of Agile Software Craftsmanship</a> — Robert C. Martin</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/0*hadhLuAGhM1UT2nB.jpg" /></figure><p>It’s hard to find a programmer who doesn’t know Clean Code. The book will tell you which code is good, which one not and how to improve them. By the end we will be guided to write unit tests. The content given are all very useful advice and I think it takes a long time to ponder and practice to instill the thought.</p><p>It’s a pity that everyone knows about the book, but not everyone really reads and ponders it. In general, knowing but not understanding.</p><p>This book is a must read, no matter who you are.</p><p>========</p><p>Above are 5 books that I find extremely useful for those who want to follow the Java path. If you know other good ones, please suggest me. Although I have done little about Java, I have never stopped learning about it.</p><p><em>Originally published at </em><a href="https://luanvv.com/blog/5-books-every-java-developer-should-read/"><em>https://luanvv.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3169a74c59b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[10 syntax in Java You should know]]></title>
            <link>https://luanvv.medium.com/10-syntax-in-java-you-should-know-7f26d7a0493c?source=rss-168e44be4c62------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f26d7a0493c</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[tips]]></category>
            <category><![CDATA[best-practices]]></category>
            <dc:creator><![CDATA[Luan Vu]]></dc:creator>
            <pubDate>Mon, 30 Aug 2021 01:52:54 GMT</pubDate>
            <atom:updated>2022-11-09T08:38:40.942Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6z8A9RSSzoin5sGgtjzhkQ.jpeg" /></figure><h4>1. Underscore in Numeric Literals</h4><p>You have to write dozen of numbers to present a number of millions, billions and even more. You always must count it again and again to make sure the number is correct.</p><p>Actually, you could place some underscore inside the number to make it clear, like you use comma in real life.</p><pre>long noUnderscore = 100000000000l;<br>long withUnderscore = 100_000_000_001l;</pre><p>Refer: <a href="https://docs.oracle.com/javase/8/docs/technotes/guides/language/underscores-literals.html">Underscores in Numeric Literals</a></p><h4>2. Pattern.asPredicate</h4><p>When use java.util.regex.Pattern with Stream API, I feel uncomfortable when I have to create a Matcher, and then use that matcher to test whether my text is matched the pattern.</p><pre>var validEmails = emails.stream()<br>        .filter(email -&gt; EMAIL_REGEX.matcher(email).find())<br>        .collect(Collectors.toList());</pre><p>I have no idea why Java make it so complex for such a simple thing. Anyway, Java provides a way to shorten the code and make it more clear. That’s Pattern.asPredicate</p><pre>var validEmails = emails.stream()<br>        .filter(<em>EMAIL_REGEX</em>.asPredicate())<br>        .collect(Collectors.<em>toList</em>());</pre><p>Refer: <a href="https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html#asPredicate--">https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html#asPredicate--</a></p><h4>3. Named RegEx Capturing Group</h4><p>When I need extract multiple information in texts with single Pattern. I have to use java.util.regex.Matcher#group and I usually pass the index of a capturing group in its pattern. The indexes always confuse me. So, you should place a named group to easily extract it by name, like this:</p><pre><strong>var</strong> p <strong>=</strong> Pattern<strong>.</strong>compile<strong>(</strong>&quot;^Today is (?&lt;month&gt;\\w+) (?&lt;day&gt;\\d+), (?&lt;year&gt;\\d+)&quot;<strong>);</strong><br><strong>var</strong> m <strong>=</strong> p<strong>.</strong>matcher<strong>(</strong>&quot;Today is August 4, 2026&quot;<strong>);</strong><br><strong>if</strong> <strong>(</strong>m<strong>.</strong>find<strong>())</strong> <strong>{</strong><br>    System<strong>.</strong>out<strong>.</strong>println<strong>(</strong>m<strong>.</strong>group<strong>(</strong>&quot;month&quot;<strong>));</strong><br>    System<strong>.</strong>out<strong>.</strong>println<strong>(</strong>m<strong>.</strong>group<strong>(</strong>&quot;day&quot;<strong>));</strong><br>    System<strong>.</strong>out<strong>.</strong>println<strong>(</strong>m<strong>.</strong>group<strong>(</strong>&quot;year&quot;<strong>));</strong><br><strong>}</strong></pre><p>Refer: <a href="https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html#special">https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html#special</a></p><h4>4. Arrays.asList</h4><p>Need to create a List inline. The fastest way is use Arrays.asList</p><pre>var numbers = Arrays.<em>asList</em>(1, 2, 3);<br>var singletonList = Arrays.<em>asList</em>(&quot;Just me&quot;);</pre><p>Beware: the list is returned is a fixed-size (but mutable) list.</p><p>Refer: <a href="https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#asList(T...)">https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#asList(T...)</a></p><h4>5. Collections.singleton*</h4><p>Do you know an ArrayList, a HashSet or a HashMap instance wastes plenty of memory even when you just need to store a single item. They need an array to store data, and int value to store real size and a HashMap (lol)</p><p>If you need a collection to store the single item, you should use:</p><ul><li>Collections.singleton to create a Set</li><li>Collections.singletonList to create a List</li><li>Collections.singletonMap to create a Map</li></ul><pre>var singletonSet = Collections.<em>singleton</em>(1);<br>var singletonList = Collections.<em>singletonList</em>(1);<br>var singletonMap = Collections.<em>singletonMap</em>(&quot;version&quot;, 1);</pre><p>It’s a simple but very effective.</p><p>Refer: <a href="https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#singleton(T)">https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#singleton(T)</a></p><h4>6. Collections.empty*</h4><p>Stop returning null value as a collection, return an empty collection instead.</p><pre>public static List&lt;String&gt; getValidEmails(Collection&lt;String&gt; email) {<br>    if (email == null) {<br>        return Collections.<em>emptyList</em>();<br>    }<br>    ...<br>}</pre><p>We have</p><ul><li>emptyList</li><li>emptyMap</li><li>emptySet</li><li>emptyIterator</li></ul><p>And more, use them.</p><p>Refer: <a href="https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#emptyList()">https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#emptyList()</a></p><h4>7. Objects equality check</h4><pre>String gameA = &quot;The Legend of Zelda: Breath of the Wild&quot;;<br>String gameB = &quot;Monster Hunter Rise&quot;;<br>System.<em>out</em>.println(gameA.equals(gameB));</pre><p>Am I seriously? Why don’t I use <strong><em>equals </em></strong>method to solve a simple thing. Well, what happened if either <em>gameA </em>or <em>gameB </em>is null? I would get an <strong><em>NullPointerException </em></strong>if I have a bad luck.</p><pre>String gameA = null;<br>String gameB = &quot;Monster Hunter Rise&quot;;<br>System.<em>out</em>.println(gameA.equals(gameB));<br>// =&gt; Exception in thread &quot;main&quot; java.lang.NullPointerException</pre><p>I can avoid it by using <strong><em>Objects.equals, </em></strong>it does work<strong><em> </em></strong>no matter either <em>gameA </em>or <em>gameB </em>is null.</p><pre>String gameA = null;<br>String gameB = &quot;Monster Hunter Rise&quot;;<br>System.<em>out</em>.println(Objects.<em>equals</em>(gameA, gameB));</pre><p>Refer: <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Objects.html#equals-java.lang.Object-java.lang.Object-">https://docs.oracle.com/javase/8/docs/api/java/util/Objects.html#equals-java.lang.Object-java.lang.Object-</a></p><h4>8. List.of, Set.of and Map.of (since 9)</h4><p>Do you prefer <a href="https://en.wikipedia.org/wiki/Functional_programming">Functional Programming,</a> and love immutable objects? Creating a immutable collection class by yourself could be changeling. Well, Java provides Unmodifiable Lists, Unmodifiable Sets, Unmodifiable Maps which basically are immutable classes.</p><p>For example, Unmodifiable Lists have some characteristics:</p><ul><li>They are <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Collection.html#unmodifiable"><em>unmodifiable</em></a>. Elements cannot be added, removed, or replaced. Calling any mutator method on the List will always cause UnsupportedOperationException to be thrown. However, if the contained elements are themselves mutable, this may cause the List&#39;s contents to appear to change.</li><li>They disallow null elements. Attempts to create them with null elements result in NullPointerException.</li><li>They are serializable if all elements are serializable.</li><li>The order of elements in the list is the same as the order of the provided arguments, or of the elements in the provided array.</li><li>They are <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/doc-files/ValueBased.html">value-based</a>. Callers should make no assumptions about the identity of the returned instances. Factories are free to create new instances or reuse existing ones. Therefore, identity-sensitive operations on these instances (reference equality (==), identity hash code, and synchronization) are unreliable and should be avoided.</li><li>They are serialized as specified on the <a href="https://docs.oracle.com/en/java/javase/11/docs/api/serialized-form.html#java.util.CollSer">Serialized Form</a> page.</li></ul><p>Refer: <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/List.html#unmodifiable">https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/List.html#unmodifiable</a></p><p>To create an unmodifiable lists, use can use <strong><em>List.of</em></strong></p><ul><li>static &lt;E&gt; List&lt;E&gt; of()</li><li>static &lt;E&gt; List&lt;E&gt; of​(E e1)</li><li>static &lt;E&gt; List&lt;E&gt; of​(E… elements)</li><li>static &lt;E&gt; List&lt;E&gt; of​(E e1, E e2)</li><li>static &lt;E&gt; List&lt;E&gt; of​(E e1, E e2, E e3)</li><li>…</li></ul><p>It sounds like <strong><em>Arrays.asList</em></strong>, but instead of a mutable list, <strong><em>List.of</em></strong> creates an immutable list and it doesn’t accept null values.</p><h4>9. Comparator and null</h4><p>In the past, I didn’t noticed that Comparator don’t work with null value by default.</p><p>For example, the code will throw a NullPointerException</p><pre>var list = Arrays.<em>asList</em>(1, null, -1, null, 2);<br>list.sort(Comparator.<em>naturalOrder</em>());<br>// ==&gt; Exception in thread &quot;main&quot; java.lang.NullPointerException</pre><p>I used to code like this</p><pre>var list = Arrays.<em>asList</em>(1, null, -1, null, 2);<br>list.sort((a, b) -&gt; {<br>    if (a == null) {<br>        return b == null ? 0 : -1;<br>    }<br>    if (b == null) {<br>        return a == null ? 0 : 1;<br>    }<br>    return a.compareTo(b);<br>});</pre><p>Luckily, there are two simple methods resolve my problem. They are <strong><em>Comparator.nullsFirst</em></strong> and <strong><em>Comparator.nullsLast</em></strong></p><pre>var list = Arrays.<em>asList</em>(1, null, -1, null, 2);<br>list.sort(Comparator.<em>nullsFirst</em>(Comparator.<em>naturalOrder</em>()));<br>// [null, null, -1, 1, 2]</pre><h4>10. Predicate::not (since 11)</h4><p>Stream API is good, filter is great and Predicate is awesome, but have you ever written something like that:</p><pre>games.stream()<br>   .filter(game -&gt; !Strings.<em>isNullOrEmpty</em>(game))<br>   .collect(Collectors.<em>toList</em>());</pre><p>Fortunately, Java 11 save you from that ugly code by <strong><em>Predicate.not</em></strong></p><pre>games.stream()<br>   .filter(Predicate.<em>not</em>(Strings::<em>isNullOrEmpty</em>))<br>   .collect(Collectors.<em>toList</em>());</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f26d7a0493c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Pass the AWS Solutions Architect Professional Exam]]></title>
            <link>https://luanvv.medium.com/how-to-pass-the-aws-solutions-architect-professional-exam-a5238782702d?source=rss-168e44be4c62------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5238782702d</guid>
            <category><![CDATA[aws-csa-pro]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[certification]]></category>
            <category><![CDATA[review]]></category>
            <dc:creator><![CDATA[Luan Vu]]></dc:creator>
            <pubDate>Sun, 29 Aug 2021 11:31:58 GMT</pubDate>
            <atom:updated>2021-08-29T11:31:58.844Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*9KdDqTaQ758oZGTZaCfNAQ.png" /></figure><p>You are looking to take the AWS Certified Solutions Architect — Professional certification exam. Today I will help you some tips &amp; tricks that I learned during my professional exam preparation two years ago.</p><h4>How I PASSED the New AWS Solutions Architect Professional?</h4><p>Another guide to the certification exam, probably reading the White Paper, watching videos on YouTube, taking this course that course, etc. No! Such those articles, are present on the internet a lot. I can get you some:</p><ul><li><a href="https://acloud.guru/forums/aws-csa-pro-2019/discussion/-L_joCzK9FTbpP2P7H0Z/how_i_passed_the_new_aws_solut">How I PASSED the New AWS Solutions Architect Professional (Feb 2019 version) exam last March 9!</a></li><li><a href="https://acloud.guru/forums/aws-csa-pro-2019/discussion/-Lc31u8nAIbpeo9q9mM7/aws_certified_solutions_archit">AWS Certified Solutions Architect — Professional 2019 (feedback)</a></li><li><a href="https://virtualbonzo.com/2020/02/03/my-aws-solution-architect-professional-certification-experience/">My AWS Solution Architect Professional Certification Experience</a></li><li><a href="https://medium.com/grey-frogs/my-path-to-aws-certified-solutions-architect-professional-bebd42eb5d5">My path to AWS Certified Solutions Architect — Professional</a></li><li><a href="https://acloud.guru/forums/aws-certified-solutions-architect-professional/discussion/-KEAY5AHdre2DzoI-H99/passed-sa-pro-today">Passed SA Pro today</a></li></ul><p>Those articles are already too many, adding one of mine is nothing more. Are the other people correct? Definitely right. But to do it is not as easy as it sounds. Learning the right route is good, but to pass the exam depends on your ability to learn and the background knowledge you have. It is said that if you study for 4 months, you will pass (I have studied for a whole year, what a shame), but you could still don’t pass no matter a whole year preparation.</p><h3>What is the standard learning path?</h3><p>In generally, The path to passing the AWS certification exam includes (don’t miss anything):</p><h4>1. Read White papers</h4><p>There are hundreds White papers, some with thousands of pages. Can you read it all? No matter how many you read, how much are you able to remember?</p><p>I just checked, now there are 314 White Paper &amp; Guide, you can check it at <a href="https://aws.amazon.com/whitepapers/?whitepapers-main.sort-by=item.additionalFields.sortDate&amp;whitepapers-main.sort-order=desc&amp;awsm.page-whitepapers-main=1">AWS Whitepapers &amp; Guides</a>.</p><p>You should read all important White Papers which mentioned in the those articles above.</p><h4>2. Read FAQs</h4><p><a href="https://aws.amazon.com/faqs/">AWS FAQs - Frequently Asked Questions about Products and Concepts - AWS</a></p><p>FAQs are also important. You should read all.</p><h4>3. Watch AWS re:Invent, This Is My Architecture in YouTube</h4><p>If you don’t have much chance to try services, architectures (like me), these videos are very helpful. They show you how a service should be use in real project (the exam too, of course) and how a group of services interact in an architecture to resolve problems.</p><p><a href="https://www.youtube.com/c/amazonwebservices/search?query=AWS%20Re%3Ainvent">Amazon Web Services</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fvideoseries%3Flist%3DPLhr1KZpdzukdeX8mQ2qO73bg6UKQHYsHb&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fplaylist%3Flist%3DPLhr1KZpdzukdeX8mQ2qO73bg6UKQHYsHb&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FLy_UhX3LCCs%2Fhqdefault.jpg%3Fsqp%3D-oaymwEWCKgBEF5IWvKriqkDCQgBFQAAiEIYAQ%3D%3D%26rs%3DAOn4CLAJVEtQkpa-AojL9GCHlsmqZuvTzA%26days_since_epoch%3D18868&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="853" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/cbd1c50e123cdb03a3b611b5fa893dc6/href">https://medium.com/media/cbd1c50e123cdb03a3b611b5fa893dc6/href</a></iframe><h4>4. Take some online/offline courses</h4><p>This is actually the easiest to access. There are many (most) AWS courses available, both paid and paid. AWS also has some Exam Readiness (Free) to guide you through the exam questions</p><p><a href="https://aws.amazon.com/training/course-descriptions/exam-workshop-solutions-architect-professional/">Exam Readiness: AWS Certified Solutions Architect — Professional</a></p><p>There are many types of courses, but in general, they are not enough. Especially some of the default courses require you to have a good knowledge of AWS, they just overview for you. If you just stick to the course, failure is certain.</p><p>I found a really valuable course on Udemy. It could be more expensive than usual but the author deserve it.</p><p><a href="https://www.udemy.com/share/104sE03@v25ocWwp5mS6EczCcLEoR6xjbdtVk0GPohkBLMVwUaLf4HB5bd4GAH_1dxW_J10=/">https://www.udemy.com/share/104sE03@v25ocWwp5mS6EczCcLEoR6xjbdtVk0GPohkBLMVwUaLf4HB5bd4GAH_1dxW_J10=/</a></p><p><em>Fun Fact: the first time I took the exam, I was hit in the face with a service called Amazon Mechanical Turk, which didn’t appear in any of the White Papers, FAQs or AWS Console. I think it is a question which isn’t scored, so don’t worry if AWS give you such a surprise like that.</em></p><h4>5. Practice</h4><p>Those learning materials are certainly informative, but it’s hard to remember them all if you just read them and watch them do it. Practicing helps you understand better, remember better. Never skip practice any service.</p><h4>6. Learn English</h4><p>It’s seriously. Depends on the certification level you take the exam. With Professional I took the exam, the question is very very long, printing must also be over 50 pages. As I read and thought of the answer, it was indeed a terrible sprint. For test takers whose native language is not English (non-English speakers or English as a Second Language), AWS allows you to request accommodations, whereby you get a bonus of 30 minutes each time, so take advantage of it.</p><p>Speaking of this, many of you are probably shocked and don’t dare to study, but that’s the truth. This test is extremely difficult, requiring hundreds of hours of study and practice. You should have really terrible determination to make it through. Fortunately, Amazon will only test you on a few key services. If you know (to the point of mastering) the key services, you have achieved over 80%. And if you don’t understand these services and lose points, then strange services you never touch will be a lifesaver, but, it is boundless knowledge. That why AWS Solutions Architect Professional is touch, it is difficult to understand something deeply, and if it is broad, it is too broad to understand it all.</p><h4>Tip &amp; Trick</h4><p>In fact, I’m not a person who has the ability to remember well. I tried to learn by going from service to service and memorize all of them. According to statistics, I have read at least 47 full books about AWS, of which about 10–20 White Papers. However, the more I try to remember, the more I forget, learning 10–20 services, forgetting the first ones, reading a lot of books also forgetting quite a bit. So, I chose to study on my own.</p><h3>Service classification</h3><p>AWS has already categorized it for you at <a href="https://aws.amazon.com/products/">https://aws.amazon.com/products/</a></p><p>Service classification is very important. It helps you know what you are facing and how you deal with it. If you face a storage service, you need to know how to secure it, how much capacity, how much availability, what about reliability. If you use Database, remember it is RDBMS or NoSQL, cache or Big data.</p><p>It also helps you to remember the service better. There are various service names you have never heard before, so classification help you have some idea about it at least. For instance, EC2 Auto Scaling or Elastic Load Balancer sounds reminiscent, but what do you think Neptune is for? Universe? Snowball, Glacier, etc.</p><h3>Based on Well-Architected Framework’s Five Pillars</h3><p>Well-Architected Framework provides guidelines to help customers deploy systems on AWS. The framework offers five main pillars:</p><ul><li>Security</li><li>Reliability</li><li>Performance Efficiency</li><li>Cost Optimization</li><li>Operational Excellence</li></ul><p>When encountering any service, you need to think along these pillars.</p><h4>1. Security</h4><p>AWS places great emphasis on security across all architects. There are 2 main types of secure that you need to know:</p><ul><li>Security operations</li><li>Data protection</li></ul><h4>Security operations</h4><p>There are always employees who do wrong things that they are not authorized to do or should not do. Those are the reasons there are services like IAM, Organizations, Cognito, CloudTrail, etc. When learning a certain service, you must know how to grant access or limit access to it. Amazon S3, how to not allow others to publish it? How do I allow someone with another AWS account (and only them) to access? How to prevent someone from Terminate EC2 instance? Knowing what a service can do is important, but securing it is just as important.</p><h4>Data protection</h4><p>You must get used to the concept of Encrypt at rest and Encrypt in transit. Is data stored in Storage encrypted? Is it encrypted when transferring data to the internet or on-premises via VPN? Most services are encrypt in transit by default, but encrypt at rest is not (EBS is not encrypted by default). There are still a lot of difficult customers out there. They require even more security. Have to use CloudHSM, use their own certificate or use end-to-end encryption too, and it’s really hard. You will become confusing with such services like KMS, CloudHSM, Direct Connect, Security Hub, Transit Gateway, VPN, etc. but it is it will appear frequently in the exam because that’s how an enterprise application is built.</p><h4>2. Resiliency: Availability and Disaster Recovery (DR)</h4><p>High Availability, Blue/Green Deployment, Zero Down Time, Uptime, service level agreement (SLA), recovery time objective (RTO), recovery point objective (RPO), Redundancy, Failback, etc. You must go into deep dives on it.</p><p>Maybe the projects you have done or are doing are all at a very basic level: 1 server, 1 database, 1 data center, etc. Stop and start again. But when it came to AWS, the standard of architecture took a new high level. Your system must be redundant for everything: hardware failure leading to server stop or data loss. Possibilities like hurricanes, earthquakes, and volcanoes destroy a data center. Even, you have to take into account the case of the main error from AWS.</p><p>You need to know 4 ways to preserve the system</p><ul><li>Backup and Restore</li><li>Pilot Light</li><li>Warm Standby</li><li>Multi-site Example</li></ul><p>For example, EC2 only guarantees 95.0% availability, which means every 1 hour EC2 can down for 3 minutes. To increase availability, need to combine with Auto Scaling Group, Load Balancer. More advanced, use Cross region Load Balancer, Multi-site between AWS infrastructure and on-premises. The Serverless option can also be considered as an alternative. What about data? EC2 stores data in EBS, how to ensure no data loss? By now you will probably have to know things like RAID, Snapshot, Point-in-time (PIT).</p><p>Similarly in RDS, we have RDS snapshot, backtrack, Replica, Multi AZ, etc. With ElastiCache there is also Multi A-Z, Failover, Append Only Files (AOF),…You also need to know, how long it takes to recover (RTO) and how much data can be lost (RPO). If customers needs to restore the system within 1 hour, storing it in Glacier is absolutely wrong.</p><p>Refer</p><ul><li><a href="https://aws.amazon.com/blogs/publicsector/rapidly-recover-mission-critical-systems-in-a-disaster/">Rapidly recover mission-critical systems in a disaster</a></li><li><a href="https://cloud.netapp.com/blog/understanding-aws-high-availability-compute-sql-and-storage">AWS High Availability: Compute, SQL and Storage</a></li><li><a href="https://aws.amazon.com/blogs/startups/high-availability-for-mere-mortals/">High Availability for Mere Mortals</a></li></ul><h4><strong>3. Performance</strong></h4><p>Performance here is understood as the use of computing resources to meet system requirements, as well as maintain performance when requirements change or technology evolves. Some of the issues raised could be:</p><ul><li>Latency</li><li>IOPS</li><li>Throughput</li></ul><p>When choosing a service to use for your architecture, there are four types of resources you need to consider: compute, storage, database, and network</p><h4><strong>Compute</strong></h4><p>There are 3 main types of compute</p><ul><li><em>Instance</em>: a virtual server, typically EC2 and Lightsail. Actually, you can use EC2 to solve everything if there is no other option. For example, launch a MySQL server inside an EC2 instance.</li><li><em>Container</em>: is a way of virtualizing the operating system, can immediately think of Docker, Kubernetes. With AWS, think about ECS, Fargate, and EKS. When to use Container instead of Instance? Most of the answers (in the test) will be customers who already use on-premises containers and want to spend the least amount of effort if migrating to AWS.</li><li><em>Function</em>: focus on code and run without having to manage instances. Functions have three important benefits: minimal management effort, great scalability, and are particularly suitable for event based programs.</li></ul><p><strong>Storage</strong></p><p>There are 3 main types of storage:</p><ul><li>Object Storage: just S3</li><li>Block Storage: just EBS</li><li>File Storage: EFS, FSx</li></ul><p>In my opinion, Storage Gateway should also be included here. The storage classification doesn’t make much sense either. With a file, you can save it in Object Storage, Block Storage or File Storage. However, there is a slight difference. Eg: S3 is limited to 3,500 PUT/COPY/POST/DELETE and 5,500 GET/HEAD requests per second per prefix (directory name), and don’t forget there’s also a KMS limit if you choose to encrypt. And yet, accessing files from S3 will have extremely high latency. Think about them when you use them. With EBS, it is necessary to know what’s the difference of the volume types, which are optimal for IOPS? Which are optimal for Throughput? If you need even higher performance, you can think of RAID, but what are the disadvantages of RAID? Data loss, Downtime. EBS still has certain limitations: IOPS, Throughput, Hybrid Storage, Limit storage size, Sharing, Availability, etc. Then you will need to use EFS.</p><p><strong>Database</strong></p><p>Databases can be divided into 7 types:</p><ul><li>Relational: RDS</li><li>Key-Value: DynamoDB, or maybe even Redis</li><li>Document: DocumentDB</li><li>In-Memory: ElastiCache, MemoryDB (new)</li><li>Graph: Neptune</li><li>Time-Series: Timestream</li><li>Ledger: QLDB</li></ul><p>Each type of database will be used for different purposes, but sometimes it is not too obvious.</p><p>Eg: Customers using MySQL on-premises does not mean that going to AWS is required to use RDS. That’s also just an option. Another option could be MySQL on EC2 instance, convert MySQL to use DynamoDB.</p><p>If you want a database with high access frequency, low latency, it can be DynamoDB, but if the data is not too important, ElastiCache is also a good choice.</p><p>In general, the database selection problem is not too difficult. Usually the question will revolve around the problem of optimizing a certain type of database.</p><p>Eg: Customer is using MySQL on RDS and is noticing slow response as traffic increases. Think about multi-writer, multi-reader and maybe even ElastiCache to reduce the load on RDS.</p><p>Refer:</p><ul><li><a href="https://www.youtube.com/watch?v=q81TVuV5u28&amp;ref=wellarchitected">AWS re:Invent 2019: Leadership session: AWS purpose-built databases (DAT209-L)</a></li></ul><h4><strong>Network</strong></h4><p>All AWS components are connected through a network, could be AWS’s private network or the internet.</p><p>EC2 instances connect to EBS through the internal network; Route53, CloudFront, S3 in/out internet; connection between AWS and on-premises,… In this regard, there are several common solutions:</p><ul><li>CloudFront can reduce latency when accessing global</li><li>Deploying (adding a system) on a region near the user is also a best way to reduce latency</li><li>Upload/Download on S3 is slow, use S3 transfer acceleration</li><li>Connecting to On-premises using VPN is slow, spend more money to use Direct Connect</li><li>Latency-Based Routing in Amazon Route 53</li><li>Use VPC Endpoints to use AWS’s internal network</li></ul><p>Refer</p><ul><li><a href="https://wa.aws.amazon.com/wat.question.PERF_1.en.html">PERF 1: How do you select the best performing architecture?</a></li><li><a href="https://wa.aws.amazon.com/wat.question.PERF_2.en.html">PERF 2: How do you select your compute solution?</a></li><li><a href="https://wa.aws.amazon.com/wat.question.PERF_3.en.html">PERF 3: How do you select your storage solution?</a></li><li><a href="https://wa.aws.amazon.com/wat.question.PERF_4.en.html">PERF 4: How do you select your database solution?</a></li><li><a href="https://wa.aws.amazon.com/wat.question.PERF_5.en.html">PERF 5: How do you configure your networking solution?</a></li><li><a href="https://wa.aws.amazon.com/wat.question.PERF_6.en.html">PERF 6: How do you evolve your workload to take advantage of new releases?</a></li><li><a href="https://wa.aws.amazon.com/wat.question.PERF_7.en.html">PERF 7: How do you monitor your resources to ensure they are performing?</a></li><li><a href="https://wa.aws.amazon.com/wat.question.PERF_8.en.html">PERF 8: How do you use tradeoffs to improve performance?</a></li><li><a href="https://wa.aws.amazon.com/wat.pillar.performance.en.html">Performance Efficiency</a></li></ul><h4>4. Cost</h4><p>Usually, there are 2 scenarios:</p><ul><li>Customers already have the system and want to reduce the price</li><li>Customers wants to migrate to AWS, for the lowest possible price.</li></ul><p>So how to optimize the price:</p><ul><li>Choose cheaper services. When to use Kinesis instead of SQS? When to use a VPN instead of Direct Connect? When to use Spot Instances?</li><li>Remove unnecessary resources.</li><li>Commitment: Savings Plans, Reserved Instances</li><li>Cost Management: Consolidated Billing, Cost Allocation Tags, Trust Advisor,…</li></ul><p>And finally, remember, optimizing for price also comes at the expense of other things (performance, availability, reliability, security, etc.). The architecture you choose may not be perfect, but if it is feasible and the most cost-effective according to the customer’s requirements, it is still the right answer.</p><h4>5. Operational Excellence</h4><p><em>“The Operational Excellence pillar includes the ability to support development and run workloads effectively, gain insight into their operations, and to continuously improve supporting processes and procedures to deliver business value”</em></p><p>It depends on services, but there are some common aspects:</p><ul><li>Infrastructure as code: in short, CloudFormation, Opsworks. You don’t need to understand what Ansible or Puppet is, but you should know what Opsworks is and what it is suitable for. You also don’t need to master CloudFormation template, but you must know some basic syntax and be able to create some services by CloudFormation, such as VPC, Subnets, RDS,…</li><li>Basic settings: some services have unique settings you must be familiar with. Eg: could I change Lambda CPU configuration? Restore a RDS snapshot, make a failover on a RDS instance? Change Launch Template, etc.</li><li>Monitoring, Incident response: logging, metric visualizer, alarms, incident management, and remediation</li><li>Some managed operator services: there are some services you should get to know, such as CloudTrail, Config, Personal Health Dashboard, Organizations, Service Catalog, Systems Manager</li></ul><p>Refer</p><ul><li><a href="https://wa.aws.amazon.com/wellarchitected/2020-07-02T19-33-23/wat.pillar.operationalExcellence.en.html">https://wa.aws.amazon.com/wellarchitected/2020-07-02T19-33-23/wat.pillar.operationalExcellence.en.html</a></li></ul><h3>Don’t trust keywords</h3><p>Many of you when taking the exam will have a trick that believe in the keyword, see this keyword, then immediately make a decision. But here, things are not so clear. If you insist on choosing the most appropriate service, it is easy to lead you to a wrong architecture, because this is a collection of services and methods, not a story of just one service.</p><p>Eg: When a customer needs a Relational database, RDS comes to mind, but don’t forget you could also use EC2 and launch the database on its instance. Why do it, because of the cost, because there are features of the database that RDS does not support.</p><p>When customers think of storing static data, you think of S3. But actually, saving in EBS, EFS is also a way.</p><p>When facing a problem, the answers will gather a lot of services and methods to solve it. Your job is to choose the most suitable method, only the most suitable service is not enough.</p><h3>Do what customers ask</h3><p>This is a very common error I encounter. Each question will present a lot of problems, you must focus on only one of it: What the customer really wants. These could be requests:</p><ul><li>How to optimize price?</li><li>How to reduce latency?</li><li>How to shorten time?</li></ul><p>Why is it a problem? Because the content of the question will be very rambling and make you think its request in a wrong way.</p><p>Eg: Customer has a website being deployed in region us-east-1, using EC2 instance and Application Load Balancer, Auto Scaling Group. The website has about 1 million users worldwide. Customers find that users accessing from Asia will experience significant latency. Ask how to optimize the price?</p><p>Global access, high latency, optimal price, you can think of CloudFront. However, CloudFront is not exactly price-optimized too much, sometimes even increasing costs, while customer requirements are price-optimized. So you have to think about Spot Instances, Reserved Instances. So, your job is to choose the answer to the question, don’t let other things distract you.</p><h3>Time management</h3><p>You have 170 minutes (or 200 minutes if you request as ESL) to solve 75 questions. However, the topic is very long. In addition to the pressure of the exam, it is easy to get immersed in some difficult questions and waste a lot of time. Try to practice solving each question within 2 or 2.5 minutes. The rest of the time will be to review the sentences marked with review.</p><p>Also do not mark the review too many, should only mark the review under 20 sentences. For questions you don’t know or think you can’t answer, answer indiscriminately and don’t look back, spend your precious time on questions that are more likely to earn points.</p><h3>Conclude</h3><p>The AWS Certified Solutions Architect — Professional exam is tough. You need a very strong determination to overcome. But whether you pass or not, it doesn’t matter, what matters is that you will gain various knowledge, and it help you in real career path.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5238782702d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Zero to PSM I, less than 24 hours!]]></title>
            <link>https://luanvv.medium.com/from-zero-to-psm-i-less-than-24-hours-96e4f80edee9?source=rss-168e44be4c62------2</link>
            <guid isPermaLink="false">https://medium.com/p/96e4f80edee9</guid>
            <category><![CDATA[psm]]></category>
            <category><![CDATA[certificate]]></category>
            <category><![CDATA[exam]]></category>
            <category><![CDATA[scrum-master]]></category>
            <dc:creator><![CDATA[Luan Vu]]></dc:creator>
            <pubDate>Sun, 22 Aug 2021 15:19:33 GMT</pubDate>
            <atom:updated>2021-08-22T15:19:33.054Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/626/0*tob9E45XWnu19KJx.jpg" /></figure><p>Sound crazy, but it’s absolutely possible. Is Professional Scrum Master I (PSM I) difficult? No! A certificate whose knowledge is only encapsulated in 19 pages is obviously not difficult. Below I will give you a study path that you can follow.</p><h3>Zero</h3><p>From the beginning, I didn’t have any concept of Scrum at all, that’s for sure. Scrum in me was just 3 months ago, started working on a project, the customer said each sprint was in 1 week, daily meetings and demo at weekend. Of course, even though I’ve worked for 3 months, I still didn’t understand what Sprint is, what Daily meetings do, or even what Scrum is. In short, nothing.</p><p>And then suddenly, a friend of mine posted a PSM I certification that they had just passed, while I was also free at that time, so I tried to take a look.</p><h3>Research</h3><p>Usually, when starting to review for a certification, I tend to buy a bunch of books and courses. I started buying 2 books about Scrum, read the first 15 pages, didn’t understand anything! So I found out more about the exam preparation path of others people on the internet, and I was really surprised, because it was so simple!</p><h3>Start</h3><p>All the knowledge you need to pass the certification exam, encapsulated in the so-called Scrum Guide, 19 pages, which you can read at <a href="https://www.scrumguides.org/scrum-guide.html">https://www.scrumguides.org/scrum-guide.html</a>. So, firstly, you need to read it.</p><h3>Scrum Guide — 10 hours</h3><p>Don’t think that reading 19 pages will make you easy to pass the exam, unless you can memorize these 19 pages exactly every word. I think you should read it many times, some people even have to read up to 10 times. I recommend only reading up to 5 times, because once you don’t understand, it’s useless to read anymore.</p><p>Reading many times, it does not mean reading continuously without stopping, this is not chanting or mantras! You should read for the first time to understand. Then watch the course (will talk about it later), then go back to read concepts you don’t understand. Then when doing the Practice test(talk later too), you should also go back to read the places you don’t understand. And finally, you should make a note section that summarizes the content of the guide, and of course you have to re-read it. In short, I calculate that I read about 5 times, each time takes 1 hour (3 minutes / page is already quite slow).</p><p><strong>Fact</strong>: I only read it once, it was when I took notes, the other 4 times I listened to it, taking advantage of the time to wash the dishes.</p><h3>Online course — 2 hours</h3><p>If you are a person who has no concept of Scrum, just reading the theory will only cause headaches. So, I recommend taking more online courses, in my opinion about $ 10, 3 Practive Test lessons and 2 hours of your life for the course is extremely worth it.</p><p>The course is here <a href="https://www.udemy.com/course/scrum-master-certification-preparation-mock-exam-questions-psm-i/">https://www.udemy.com/course/scrum-master-certification-preparation-mock-exam-questions-psm-i/</a></p><p>The content of the course, is not be outside the Scrum Guide, however, the course will give you more visual examples and provide some tips &amp; tricks for the exam. I consider this course to be the most important key, especially for some one who have no idea about Scrum (like me).</p><p><strong>Note</strong>: you can skip the live webinar, as it’s not very relevant to the test.</p><p><strong>Fact</strong>: I also took advantage of the time to wash the dishes to watch the entire 2 hours of the course</p><h3>Practice test — 10 hours</h3><p>Practice tests are also extremely important. Knowledge is clearly only in 19 pages, so the question set of the real exam cannot be boundless. According to my experience, there will be about 60% of the questions in the exam that are quite close to the Practice tests. In addition, doing a lot of Practice tests will help you get used to the speed of the test, practice fast thinking.</p><p>In fact, when I took the exam, it only took me 40 minutes for 80 questions, the remaining 20 minutes I spent reviewing 7–8 questions.</p><p>Some tests you can refer:</p><ul><li><a href="https://mlapshin.com/index.php/scrum-quizzes/sm-learning-mode/">https://mlapshin.com/index.php/scrum-quizzes/sm-learning-mode/</a> (Free). You can try Real Mode, but I think there is no need, because the topic here is quite simple, Real or Learning also not very different.</li><li><a href="https://www.scrum.org/open-assessments/scrum-open">Open Assessments</a> (Free). This topic by the owner should be completely same level of the real test. However, they only gave 30 questions and did it in 30 minutes</li><li>3 Practice tests in the course I have introduced above</li></ul><p>After learning all the above knowledge, the practice tests are not too difficult, I usually only take about 40 minutes for each test with over 80 questions, the rest time is to review. So I keep counting about 90 minutes at a time. When doing a certain sentence, you should practice looking at the keywords of the sentence and the method of exclusion. Also, your English shouldn’t be too bad. For example, I have didn’t know the word “<em>prohibit</em>” means “<em>forbidden</em>”, so when I took the test, I got 1 wrong sentence. So, improve your vocabulary in practice tests.</p><p>You should score above 80% in Practice tests. In the course I mentioned above, there were 3 tests, I did it over and over again, a total of about 5 times. The article on <a href="https://mlapshin.com/">https://mlapshin.com</a> I only did once, because it was too easy. Open Assessments also only do it once, because I’m pretty sure all of them.</p><p>When reviewing the test you did, never try to remember the question and the answer. Please read questions, answers and explanations carefully, refer to the Scrum Guide for understanding. If you just try to memorize them, you will get stuck on puns during the real exam. When I took the real test, I was very surprised because they had about 30% of the questions much more difficult than the Practice test. Those questions had slightly change the wording, the answers also sounded different from the Scrum Guide, but in fact, they are never outside the Scrum Guide. Therefore, understanding is extremely important.</p><p>When you are confident, it’s time to take the test.</p><p><strong>Fact</strong>: I can’t take advantage of this while washing the dishes, because my hands are covered with soap. I usually take advantage before going to bed or free afternoon, even in some boring meetings.</p><h3>Exam, 1 hour 10 minutes</h3><p>Below are the details of the exam, to see the latest updates, you should visit the homepage at <a href="https://www.scrum.org/professional-scrum-master-i-certification#Details">https://www.scrum.org/professional-scrum-master-i-certification#Details</a></p><ul><li>Fee: $150 USD per attempt</li><li>Passing score: 85%</li><li>Time limit: 60 minutes</li><li>Number of Questions: 80</li><li>Format: Multiple Choice, Multiple Answer and True/False</li><li>Difficulty: Intermediate</li><li>Language: English only</li><li>Scrum Resources</li><li>Required course: None</li><li>Recommended courses: <a href="https://www.scrum.org/courses/professional-scrum-foundations-training">Professional Scrum Foundations</a> or <a href="https://www.scrum.org/courses/professional-scrum-master-training">Professional Scrum Master</a></li><li><a href="https://www.scrum.org/resources/suggested-reading-professional-scrum-master">PSM Subject Areas</a></li><li>Practice Assessment: <a href="https://www.scrum.org/open-assessments/scrum-open">Scrum Open</a></li><li>Ways to <a href="https://www.scrum.org/resources/ways-learn-about-scrum">Learn More</a> to help you prepare</li><li>Passwords have no expiration date, but are valid for one attempt only</li></ul><p>The exam is an online testing, at home, you can comfortably use everything. However, the number of questions is quite large (80 questions), the time is (too) short (60 minutes) and the score is very high (85%), every mistake, no matter how small, comes at a price, so keep focus.</p><p>A huge disadvantage of online exams, is the speed of the network. If your network is slow or your computer is slow, it’s a disaster. Don’t forget the notes I mentioned above, it will be convenient for you to look up. Another thing is that when you click Next, Previous, pay special attention, during the page load, you may click again and choose the wrong answer again. Or if your hands are shaking too much, it’s easy to reload the page or close the tab/browser by accident, I don’t know if it’s okay, but it’s obviously going to be a problem. Be careful on each touch.</p><p>To register the test is quite simple. You register an account on <a href="https://www.scrum.org/,">https://www.scrum.org/,</a> buy Assessment, a password will be sent to your email and you can start taking the test immediately with the password you just received.</p><h3>Result</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*DG8H-PImx7_n1gKcw1ShfQ.png" /></figure><p>So I have summarized the PSM I learning in just 23 hours and 10 minutes. In fact, it took me a week to study and take the exam, because I didn’t wash the dishes 24 hours in a row. My friend has took only 4 days. I think with only 2 days of continuous learning, the total time could be less than 23 hours.</p><p>However, writing articles is how I do it, but $150 is yours to spend, and this is not a speed contest, so don’t be too hasty to lose your money. Take the test when you are ready. Good luck.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96e4f80edee9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot project using AWS RDS and Secrets Manager]]></title>
            <link>https://luanvv.medium.com/spring-boot-project-using-aws-rds-and-secrets-manager-624590e2e49d?source=rss-168e44be4c62------2</link>
            <guid isPermaLink="false">https://medium.com/p/624590e2e49d</guid>
            <category><![CDATA[secrets]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[rds]]></category>
            <category><![CDATA[jdbc]]></category>
            <dc:creator><![CDATA[Luan Vu]]></dc:creator>
            <pubDate>Sun, 22 Aug 2021 14:26:33 GMT</pubDate>
            <atom:updated>2021-08-22T14:26:33.095Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*p97n45ofigscZpO8K2EwLQ.jpeg" /></figure><p>In this article, I will show you how to integrate Amazon RDS connection information into a Spring project using AWS Secrets Manager.</p><p>With traditional Spring projects, we tend to configure the data source directly inside the source code. In different environments (development, staging, production), it is common to use Spring profiles to change these parameters. This solution is convenient, but it lacks security (credentials explosion, inability to access manager), difficult to manage and change (password rotation policy).</p><p>AWS offers a solution using <a href="https://aws.amazon.com/secrets-manager/">AWS Secrets Manager</a> integration with RDS and <a href="https://docs.aws.amazon.com/secretsmanager/latest/userguide/rotating-secrets.html">Rotating Secrets</a>, simplifying management and ensuring security. Refer to <a href="https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_BestPractices.Security.html">Security best practices for Amazon RDS</a></p><p>Here are 2 simple steps to integrate RDS data source and Spring Boot project using AWS Secrets Manager.</p><h4>Step 1. Add this dependency in pom.xml file</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da2e00f9d24d3ff7f79d2ac621bbba65/href">https://medium.com/media/da2e00f9d24d3ff7f79d2ac621bbba65/href</a></iframe><p>Step 2. Change data source configuration</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f271e7c7f666ff7d19b224f73d7c7a2e/href">https://medium.com/media/f271e7c7f666ff7d19b224f73d7c7a2e/href</a></iframe><ul><li>url: it has a prefix <em>jdbc-secretsmanager</em> instead of just <em>jdbc</em> as usual</li><li>username: <em>Secret Name </em>which you’ve got in AWS Secrets Manager</li></ul><p>The magic here is that <em>driver-class-name</em> is <em>AWSSecretsManagerMySQLDriver.</em> It is the AWS Secrets Manager Driver driver which wraps the original driver (for instance <em>com.mysql.cj.jdbc.Driver</em>).</p><p>Some databases and corresponding drivers:</p><ul><li><strong>MySQL</strong>: <em>AWSSecretsManagerMySQLDriver</em></li><li><strong>MariaDB</strong>: <em>AWSSecretsManagerMariaDBDriver</em></li><li><strong>Oracle DB</strong>: <em>AWSSecretsManagerOracleDriver</em></li><li><strong>PostgreSQL</strong>: <em>AWSSecretsManagerPostgreSQLDriver</em></li><li><strong>MSSQL</strong>: <em>AWSSecretsManagerMSSQLServerDriver</em></li></ul><p>Here is a <a href="https://github.com/luanvuhlu/rds-secrets-sample">GitHub link</a> to this implementation.</p><p>So it’s done. Now you can use Spring data source normally. You can rotate your password automatically every day, every month in AWS Secrets Manager and your program will still work as you expected without restarting every time you change the password.</p><p>But How? If you need to understand in more detail how it works, continue to follow below.</p><h4>How it work</h4><p>When the program needs a JDBC connection, the java.sql.Driver#<em>connect </em>function is called. Instead of retrieving an existing username/password, the Driver wrapper (eg AWSSecretsManagerMySQLDriver) will call into the AWS Secrets Manager to retrieve the username/password.</p><p>The problem is that you have to calls the AWS Secrets Manager API every time you use the connection, it will take time and cost a lot(AWS Secrets Manager charges by the number of API calls). So, the better way is to cache and reuse username/password next time instead of calling AWS Secrets Manager.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*iNCoc23IcK_xcoK_YYWoSg.png" /></figure><p>If the cached has expired (default is 1 hour), the driver will continue to call into AWS Secrets Manager to retrieve the username/password (can be new or old).</p><p>So what if the cached has not expired but the username/password in AWS Secrets Manager(also in RDS of course) has been changed? Driver uses fallback mechanism. It doesn’t know credentials are changed, so it continuous connects to database using the existing username/password (in the cached), if the database returns an error indicating the wrong username/password, call AWS Secrets Manager to get the new username/password.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*5KLKq57Kce3SdmpVjnm2gg.png" /></figure><p>And that’s it. Above is the guide on how to integrate Amazon RDS and AWS Secrets Manager into Spring Boot project. This method is not limited to Spring but can be used with any Java project that uses JDBC.</p><h3>Reference</h3><ul><li><a href="https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_BestPractices.Security.html">https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_BestPractices.Security.html</a></li><li><a href="https://docs.aws.amazon.com/secretsmanager/latest/userguide/rotating-secrets.html">https://docs.aws.amazon.com/secretsmanager/latest/userguide/rotating-secrets.html</a></li><li><a href="https://dzone.com/articles/spring-boot-handle-aws-rds-password-change-or-rota">https://dzone.com/articles/spring-boot-handle-aws-rds-password-change-or-rota</a></li><li><a href="https://github.com/aws/aws-secretsmanager-jdbc">https://github.com/aws/aws-secretsmanager-jdbc</a></li><li><a href="https://aws.amazon.com/blogs/security/use-aws-secrets-manager-client-side-caching-libraries-to-improve-the-availability-and-latency-of-using-your-secrets/">https://aws.amazon.com/blogs/security/use-aws-secrets-manager-client-side-caching-libraries-to-improve-the-availability-and-latency-of-using-your-secrets/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=624590e2e49d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>