<?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 Ahad Azarian on Medium]]></title>
        <description><![CDATA[Stories by Ahad Azarian on Medium]]></description>
        <link>https://medium.com/@ahad.azarian?source=rss-a6ca5afe8380------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2MHKG5jJjnJRDthWyYHnzA.jpeg</url>
            <title>Stories by Ahad Azarian on Medium</title>
            <link>https://medium.com/@ahad.azarian?source=rss-a6ca5afe8380------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 00:10:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ahad.azarian/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[Query Writing Methods in JPA and Hibernate]]></title>
            <link>https://medium.com/@ahad.azarian/query-writing-methods-in-jpa-and-hibernate-3976559f2601?source=rss-a6ca5afe8380------2</link>
            <guid isPermaLink="false">https://medium.com/p/3976559f2601</guid>
            <dc:creator><![CDATA[Ahad Azarian]]></dc:creator>
            <pubDate>Sat, 09 Sep 2023 17:24:04 GMT</pubDate>
            <atom:updated>2023-09-09T17:24:04.295Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we explore database access in Spring Boot’s<a href="https://www.javaguides.net/2020/07/spring-boot-project-architecture.html"> three-tier architecture</a>. We’ll dive into various query writing techniques and help you in selecting the most suitable approach for your needs.</p><h3>1. Review Hibernate and JPA</h3><p>Hibernate serves as an intermediary layer between a Java application’s data access and the Relational Database, as depicted in the diagram. It provides essential APIs for loading, storing, and querying domain data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/0*jTyJ97IO-JMgvFoL" /><figcaption><a href="https://docs.jboss.org/hibernate/orm/6.0/userguide/html_single/Hibernate_User_Guide.html">Hibernate Architecture</a></figcaption></figure><p><strong>Data Access Layer (DAL)</strong> is a software layer that separates the logic for accessing and manipulating data from the rest of the application’s business logic. In Spring Boot the r<strong>epository classes</strong> as data access layer responsible for database operations. It sits between the business-logic layer and the data storage system and provides an abstraction layer that allows the business-logic layer to interact with the data storage system without being aware of its specific implementation.</p><p><strong>JPA(Java Persistence API)</strong> is part of the Java EE (Enterprise Edition) ecosystem. It is only a specification not an implementation, the latest JSR(Java Specification Request) for JPA is<a href="https://download.oracle.com/otn-pub/jcp/persistence-2_2-mrel-eval-spec/JavaPersistence.pdf"> here</a>. JPA defines a standard which features a library must support to be JPA compliant. And there’s a couple of libraries, like Hibernate, EclipseLink or TopLink that <em>all</em> implement the JPA specification.</p><p><strong>The Hibernate native API,</strong> sometimes referred to as the Hibernate session API, allows developers to interact with databases using Hibernate-specific classes and methods.</p><p><strong>JDBC(Java database connectivity) </strong>is the most low-level way to access databases in Java. JDBC provides a standardized way for Java applications to connect to and manipulate data stored in various DBMS like MySQL. It is used in most libraries like Hibernate, JOOQ, EclipseLink, and OpenJPA to connect and execute database operations. Find more<a href="https://www.marcobehler.com/guides/jdbc"> here</a>.</p><h3>Exploring Query Writing Methods</h3><p>There are different ways of writing queries in JPA and Hibernate.</p><ol><li><strong>Derived queries or query methods </strong>(JPA):</li></ol><p>Derived queries allows developers to define database queries based on the method names in the repository interface. By following a specific naming pattern, Spring Data JPA can automatically derive the queries from the method names and parameters. This feature eliminates the need to write custom JPQL or Native queries. You can find more about this way<a href="https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods"> here.</a></p><p>It’s important to note that while query methods are powerful for simple queries, more complex queries may require custom JPQL/SQL queries.</p><pre>@Repository<br>public interface UserRepository extends JpaRepository&lt;User, Long&gt;{<br>Optional&lt;User&gt; findByUsername(String username);<br>}</pre><p><strong>2. JPQL queries </strong>(JPA):</p><p>JPQL(Java Persistence Query Language) queries are written using the entity classes and their attributes instead of raw SQL queries, making them more type-safe and less error-prone. It is an abstraction over the underlying database and ORM and provides a platform-independent way of querying the data.</p><pre>@Repository<br>public interface UserRepository extends JpaRepository&lt;User, Long&gt; {<br>@Query(&quot;SELECT u FROM User u WHERE u.username = :username&quot;)<br>Optional&lt;User&gt; findByUsernameInJpql(String username);<br>}</pre><p><strong>3. HQL queries </strong>(Hibernate):</p><p><a href="https://www.tutorialspoint.com/hibernate/hibernate_query_language.htm">HQL</a>(Hibernate Query Language) is a powerful object-oriented query language used in Hibernate ORM.<a href="https://howtodoinjava.com/hibernate/complete-hibernate-query-language-hql-tutorial/#:~:text=HQL%20is%20a%20superset%20of,like%20%E2%80%9Cfrom%20Product%20p%E2%80%9C."> HQL</a> is a superset of the JPQL. A JPQL query is a valid HQL query, but not all HQL queries are valid JPQL queries. You can find a complete working project<a href="https://www.javaguides.net/2023/03/hibernate-6-example-tutorial.html"> here.</a></p><pre>public Optional&lt;User&gt; findByUsernameInHql(String username) {<br>try (Session session = HibernateConfig.getSessionFactory().openSession()) {<br>Query&lt;User&gt; query = session.createQuery(&quot;FROM User u WHERE u.username = :username&quot;, User.class);<br>query.setParameter(&quot;username&quot;, username);<br>return query.uniqueResultOptional();<br>}<br>}</pre><p><strong>4. Criteria queries </strong>(JPA and Hibernate)<strong>:</strong></p><p>Criteria queries provide a type-safe and object-oriented approach to create queries based on the entity’s attributes and relationships. They are well-suited for scenarios where search parameters can change dynamically, such as in web applications with search forms.</p><pre>public Optional&lt;User&gt; findByUsernameInCriteria(String username) {<br>try (Session session = HibernateConfig.getSessionFactory().openSession()) {<br>CriteriaBuilder cb = session.getCriteriaBuilder();<br>CriteriaQuery&lt;User&gt; cq = cb.createQuery(User.class);<br>Root&lt;User&gt; root = cq.from(User.class);<br>cq.select(root).where(cb.equal(root.get(&quot;username&quot;), username));<br>Query&lt;User&gt; query = session.createQuery(cq);<br>return Optional.ofNullable(query.uniqueResult());<br>}<br>}</pre><p><a href="https://www.baeldung.com/hibernate-criteria-queries"><em>Since Hibernate 5.2</em></a><em>, </em>the Hibernate criteria API is deprecated, and new development is focused on the<a href="https://www.tutorialspoint.com/jpa/jpa_criteria_api.htm"> JPA criteria API</a>.</p><pre>lic Optional&lt;User&gt; findByUsernameInCriteria(String username) {<br>CriteriaBuilder cb = entityManager.getCriteriaBuilder();<br>CriteriaQuery&lt;User&gt; cq = cb.createQuery(User.class);<br>Root&lt;User&gt; root = cq.from(User.class);<br>cq.select(root).where(cb.equal(root.get(&quot;username&quot;), username));<br>Query&lt;User&gt; query = session.createQuery(cq);<br>return Optional.ofNullable(query.uniqueResult());<br>}</pre><p>5. <strong>Native queries </strong>(JPA and Hibernate):</p><p><a href="https://www.tutorialspoint.com/hibernate/hibernate_criteria_queries.htm">Native SQL</a> queries allow us to use the database-specific SQL syntax and features directly in the queries. It is string-based, and lacks the type-safety offered by JPQL. Mistakes in the SQL syntax or attribute names might only be caught at runtime. It is possible to write native query in Hibernate. Here we used JPA.</p><pre>@Repository<br>public interface UserRepository extends JpaRepository&lt;User, Long&gt; {<br>@Query(nativeQuery = true, value = &quot;SELECT * FROM users u WHERE u.username = :username&quot;)<br>Optional&lt;User&gt; findByUsernameInNative(String username);<br>}</pre><h3>Choosing Query Writing Methods</h3><ol><li><strong>Abstraction Layers:<br></strong>Selecting high-level abstractions promotes a more modular, flexible, partable, and maintainable software architecture, enabling easy adaptation to changing requirements and enhancing overall code quality. As we know, native query has the lowest abstraction layer. Selecting the appropriate query approach follows a straightforward principle: for database-specific queries, we use native queries; otherwise, we prefer JPQL. If you’re not using JPA, HQL is the recommended option.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oJu8GBDSDIsmHSkI" /><figcaption>Abstraction layer of query writing methods</figcaption></figure><p>2. <strong>Pagination and type-safety<br></strong>In native queries, additional steps, such as adding a countQuery, are required for pagination. Type safty doesn’t check in compile time in native queries. From Hibernate 6.0, it provides better type safty checking.</p><p>3.<strong> Caching:<br></strong>Hibernate invalidates the second level cache when you execute a native SQL UPDATE or DELETE statement because these statements can modify data in the database, potentially affecting cached entities. Hibernate, by default, lacks awareness of which records were altered, so it opts to invalidate the entire second level cache. It is possible to define a specific class to be synchronized after running a query. You can find more details<a href="https://thorben-janssen.com/hibernate-tip-how-to-control-cache-invalidation-for-native-queries/"> here</a>.</p><p><strong>4. Refactoring:<br></strong>Updating a table name or columns based on entity class can not be done automatically inside the string literals, specially when we are using native query, it needs more effort.<br>For writing multiline queries with any method, ryou can utilize<a href="https://docs.oracle.com/en/java/javase/17/text-blocks/index.html"> Java text block feature</a>, which becomes available starting from Java 15. The text block version offers improved readability and easier maintenance.</p><pre>String query = &quot;&quot;&quot;<br>SELECT u<br>FROM USER u<br>WHERE u.username = :username<br>&quot;&quot;&quot;;</pre><p><strong>Thank you</strong> for taking the time to explore this article. If you found it informative, or simply enjoyed the read, your support through likes energizes me to create even better content. Happy reading!</p><p>To connect with me on LinkedIn, please visit<a href="https://www.linkedin.com/in/ahad-azarian-067120a8/"> here</a>.</p><p><strong>References:</strong></p><p><a href="https://www.marcobehler.com/guides/jdbc">JDBC — a short guide<strong><br></strong><em>You can use this guide to learn the basics of JDBC: How to connect to any database and execute SQL queries.</em>www.marcobehler.com</a><br><a href="https://www.javaguides.net/2023/03/hibernate-6-example-tutorial.html">https://www.javaguides.net/2023/03/hibernate-6-example-tutorial.html<br></a><a href="https://www.javaguides.net/2020/07/spring-boot-project-architecture.html">https://www.javaguides.net/2020/07/spring-boot-project-architecture.html<br></a><a href="https://thorben-janssen.com/hibernate-tip-how-to-control-cache-invalidation-for-native-queries/">https://thorben-janssen.com/hibernate-tip-how-to-control-cache-invalidation-for-native-<br></a><a href="https://docs.oracle.com/en/java/javase/17/text-blocks/index.html">https://docs.oracle.com/en/java/javase/17/text-blocks/index.html</a><a href="https://thorben-janssen.com/hibernate-tip-how-to-control-cache-invalidation-for-native-queries/">queries/</a><a href="https://www.tutorialspoint.com/jpa/jpa_criteria_api.htm">https://www.tutorialspoint.com/jpa/jpa_criteria_api.htm<br></a><a href="https://www.tutorialspoint.com/hibernate/hibernate_criteria_queries.htm">https://www.tutorialspoint.com/hibernate/hibernate_criteria_queries.htm</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3976559f2601" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot Data Access Layer Best Practices]]></title>
            <link>https://towardsdev.com/spring-boot-data-access-layer-best-practices-c544d400de7b?source=rss-a6ca5afe8380------2</link>
            <guid isPermaLink="false">https://medium.com/p/c544d400de7b</guid>
            <category><![CDATA[data-access-layer]]></category>
            <category><![CDATA[hibernate]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[jpa]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Ahad Azarian]]></dc:creator>
            <pubDate>Thu, 10 Mar 2022 04:59:48 GMT</pubDate>
            <atom:updated>2023-09-09T17:28:42.813Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we review best practices that are very effective in optimizing spring boot data access layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7tCYY1RarI-C0PzjCVhTWQ.png" /></figure><p>Spring boot JPA has added some interface on JPA. JPA is only a specification not an implementation. There are various ORMs that implement JPA such as Hibernate and EclipseLink.</p><p>Hibernate provides many benefits like object-mapping, caching, multiple transactions, database independent queries, etc. But It has to manage the lifecycle of each entity (transient, managed, detached, removed) that causes a little overhead. But lack of sufficient knowledge on how to use it can cause serious performance problems and may cause product failure.</p><p>For optimizing application data access layers based on Spring boot JPA and Hibernate, these tips and references are recommended.</p><p><strong>Monitoring and Testing</strong></p><ul><li>For 100% database compatibility between production and test, use test containers instead of in-memory databases (H2, Fongo) for tests.</li><li>Use unit tests to assert and count SQL statements to ensure your code does not generate additional queries. Use this <a href="https://github.com/AnghelLeonard/Hibernate-SpringBoot/tree/master/HibernateSpringBootCountSQLStatements">link</a> for more information.</li><li>Log slow query with threshold by adding this line to the configuration file(It available in Hibernate 5.4.5+), otherwise use third-party libraries such as <em>datasource-proxy.</em></li></ul><pre>hibernate.session.events.log.LOG_QUERIES_SLOWER_THAN_MS=30</pre><p><strong>Transactions</strong></p><p>In transactions, we should work with read-only and small transactions as much as possible. Following instructions help us to improve transactions performance:</p><ul><li>Use these configurations to postpone connection acquisition until it’s really needed:</li></ul><pre>spring.datasource.hikari.auto-commit=false<br>spring.jpa.properties.hibernate.connection.provider_disables_autocommit=true</pre><ul><li>Use<em> @Transactional(readOnly=true)</em> to load entities in read-only state.</li><li><em>@Transactional()</em> load entity in read-write state. Read-only state is much cheaper than the read-write state.</li><li>Don’t use <em>@Transactional() </em>on private or protected methods. Because it doesn’t work in this mode.</li><li>Use <em>@Transactional(readOnly=true)</em> in Repository Interfaces and <em>@Transactional()</em> in service methods that have updating or creation operations (or any methods that need to run as a single transaction).</li><li>Don’t use <em>@Transactional()</em> in service or controller classes.</li><li>Refactor long during transaction methods to decrease transaction running time. Break them into smaller transactions.</li></ul><p><strong>Id Generation Type</strong></p><ul><li>Don’t use GenerationType.AUTO, because in Mysql it maps to GenerationType.TABLE that causes three queries when you want to insert a new row.</li><li>GenerationType.SEQUENCE is a good choice. But, if the underlying DBMS is not able to support it, use GenerationType.IDENTITY (in Mysql).</li><li>Don’t use composite keys and long keys as a primary key. Avoid using UUID/GUID as a primary key, because it is random and it causes re-organisation of the B-tree and finally it decreases performance.</li><li>ID ( primary key) must be stable (no need to update), unique, not null and simple.</li></ul><p><strong>Associations and Relations</strong></p><p>We should prevent creating unexpected tables and executing more SQL statements. Consider these:</p><ul><li>Use bidirectional <em>@OneToMany</em> associations(1⇆m) instead of unidirectional ones(1→m).</li><li>Using<em> @JoinColumn</em> can provide benefits in unidirectional @OneToMany, but still bidirectional <em>@OneToMany better </em>than it.</li><li>Unidirectional <em>@ManyToOne </em>is totally efficient.</li><li>Always use cascading from parent-side to child-side.</li><li>In <em>@OneToMany, </em>when loading entities in multiple sessions or working with detached entities, override equals() and hashCode() methods.</li><li>In any relationship type, use lazy fetching for each part of the associations.( <em>E.g.</em> <em>@ManyToOne(fetch = FetchType.LAZY)</em>)</li><li>In <em>@ManyToMany</em> choose the owner of the relationship and use Set instead of List.</li></ul><p><strong>Fetching and Queries</strong></p><ul><li>When you don’t want to change the requested entity, use DTO to map fetched read-only entities.</li><li>When to want modify an entity and need to load the child side of relation use <em>JOIN Fetch</em> in JPQL query instead of <em>eager</em> loading. If we want to fetch all entities on the left side then we use <em>LEFT JOIN FETCH</em>.</li><li>In JPQL/SQL, <em>JOIN</em> maps to <em>INNER JOIN and LEFT/RIGHT/FULL JOIN equals to LEFT/RIGHT/FULL OUTER JOIN.</em></li><li><em>Explicit JOIN is better than implicit JOIN. In some cases implicit JOIN maps to CROSS JOIN not INNER JOIN.</em></li><li>In parent-child entity queries when using JOIN FETCH, the result might contain object reference duplicates. It duplicates the parent record for every child row that’s going to be fetched. The DISTINCT keyword should only be applied after the ResultSet is obtained from JDBC, therefore using INT_PASS_DISTINCT_THROUGH instead of DISTINCT is recommended. Don’t use this method for scalar queries.</li><li>Using Spring built-in methods <em>findById()</em>, <em>find()</em>, or <em>get()</em> to fetch an entity by id is better than fetching it by specific <em>JPQL/SQL</em> query. These methods use the Hibernate caching mechanism ( First Level cache-&gt;Second Level cache-&gt;database), but <em>JPQL/SQL</em> queries fetch directly from the database.</li><li>For fetching an entity we can use Spring built-in methods, <em>findById() </em>(it uses EntityManager#find() and return exact the declared model) or <em>getOne()(it</em> uses EntityManager#getReference() and return Hibernate-specific proxy object)</li><li>In <em>@ManyToOne </em>or <em>@OneToOne associations, when </em>we need to persist a child entity with reference to its parent entity, <em>It’s better to use getOne()</em> to get the parent side.</li><li>In flush time,Hibernate finds modified properties in the entity and updates them based on the dirty checking mechanism. Don’t use save() method in the updating task, because it is a duplicated task and causes additional Hibernate specific-internal operations(MergeEvent). Of Course, using save() method doesn’t generate additional queries.</li><li>To avoid N+1 problems (executing 1 query to retrieve the parent and N queries to retrieve the child entities), use JOIN FETCH or entity graph.</li><li><em>Always use pagination to make the result set as small as possible.</em></li><li>Open Session In View(OSIV) tries to avoid LazyInitializationException by binding a JPA EntityManager to request thread lifecycle. It is a bad approach and anti-pattern, the business layer should determine the fetching approach. It also causes a performance penalty. Use this configuration to turn of OSIV:</li></ul><pre>spring.jpa.open-in-view=false</pre><ul><li>A cache execution plan decreases load by caching prepared execution plans. The plan can be reused without the optimization overhead. If the RDBMS doesn’t cache execution plans(Mysql) then caching via IN clause parameter padding only increases the complexity of the statement and might slow down the query.</li><li><em>If you have a lot of queries, alter Hibernate Query Plan Cache (QPC) to cover all queries in your application. The default size for JPQL and Criteria API is 2048 and for native queries is 128.</em></li></ul><pre>spring.jpa.properties.hibernate.query.plan_cache_max_size = 3000<br>spring.jpa.properties.hibernate.query.plan_parameter_metadata_max_size=200</pre><ul><li>In oneToMany association, if you detach an entity, update it and save it, then this save() method causes an additional select join query. To avoid it and optimize merge operation by update, use Hibernate session update() method instead of JPA save() method directly.</li></ul><pre>val session=entityManager.unwrap(Session::class.java)<br>session.update(yourEntity)</pre><ul><li>deleteAllBySomeColumn fetches all by some column (findAllBySomeColumn) then deletes them. It is not performant and using JPQL(“Delete from x where x.col1=:col1”) is a good way when we don’t need the deleted items.</li></ul><p><strong>Persistence Context</strong></p><ul><li><em>To clear persistence context after query execution, use @Modifying(clearAutomatically = true). It may delete unsaved changes.To prevent from deleting non-flushed entities in persistence context use @Modifying(flushAutomatically = true).</em></li><li>Persistence context is a first-level cache that sits between application and database. Hibernate uses it to handle the lifecycle of entities. For checking the status of entity in persistence context, this small code is helpful (Kotlin code) <strong>:</strong></li></ul><pre><em>@PersistenceContext<br>private val entityManager: EntityManager? = null<br>Val persistenceContext= entityManager.unwrap(SharedSessionContractImplementor::class.java).persistenceContext</em></pre><p><strong>Element Collections</strong></p><ul><li><em>Use @ElementCollection with embedded or basic type not an entity. In this case,any crud operations one the embedded object are limited directly and you need the parent side to do these actions.</em></li><li><em>Don’t use @ElementCollection when you have a lot of inserts/deletes on the collection. It causes Hibernate to execute a lot of insertions/deletion operations that are not needed.</em></li></ul><p><strong>Pagination and Hibernate Types</strong></p><ul><li>Use powerful filtering (keyset pagination) instead of using offset pagination. offset method decreases performance in large databases because of fetching and dropping many rows.</li><li>When you need additional types(e.g., json) that are not supported by Hibernate ORM core, use the Hibernate Types <a href="https://github.com/vladmihalcea/hibernate-types">repository</a>.</li></ul><p><strong>Thank you</strong> for taking the time to explore this article. If you found it informative, or simply enjoyed the read, your support through likes energizes me to create even better content. Happy reading!</p><p>To connect with me on LinkedIn, please visit<a href="https://www.linkedin.com/in/ahad-azarian-067120a8/"> here</a>.</p><p><strong>References</strong></p><p>There are three guys that created a lot of valuable documentation about Hibernate and Spring JPA:</p><ol><li><a href="https://www.linkedin.com/in/vladmihalcea/">Vlad Mihalcea</a> : He is a true champion in his career. He has provided various tutorial content and tools.</li><li><a href="https://www.linkedin.com/in/thorbenjanssen/">Thorben Janssen</a>: He is an active person with a lot of tutorial content.</li><li><a href="https://www.amazon.com/Anghel-Leonard/e/B00E760Y4K%3Fref=dbs_a_mng_rwt_scns_share">Anghel Leonard</a>: He has written several interesting books.</li></ol><p>I recommend these references very highly:</p><ol><li><a href="https://vladmihalcea.com/tutorials/hibernate/">https://vladmihalcea.com/tutorials/hibernate/</a></li><li><a href="https://github.com/vladmihalcea/hibernate-types">https://github.com/vladmihalcea/hibernate-types</a></li><li>Leonard, A. (2020). Spring Boot Persistence Best Practices: Optimize Java Persistence Performance in Spring Boot Applications. United States: Apress.</li><li><a href="https://thorben-janssen.com/join-persistence-hub">https://thorben-janssen.com/join-persistence-hub</a></li><li>h<a href="https://github.com/AnghelLeonard/Hibernate-SpringBoot">ttps://github.com/AnghelLeonard/Hibernate-SpringBoot</a></li><li><a href="https://www.codeo.co.za/blog/database-performance-if-youre-not-first-youre-last">https://www.codeo.co.za/blog/database-performance-if-youre-not-first-youre-last</a></li><li><a href="https://use-the-index-luke.com/no-offset">https://use-the-index-luke.com/no-offset</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c544d400de7b" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/spring-boot-data-access-layer-best-practices-c544d400de7b">Spring Boot Data Access Layer Best Practices</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Protobuf and gRPC In Action With Kotlin]]></title>
            <link>https://towardsdev.com/the-grpc-and-protobuf-in-action-with-kotlin-cf5296887856?source=rss-a6ca5afe8380------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf5296887856</guid>
            <category><![CDATA[protobuf]]></category>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Ahad Azarian]]></dc:creator>
            <pubDate>Thu, 13 Jan 2022 12:51:45 GMT</pubDate>
            <atom:updated>2022-01-21T08:12:38.221Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xZXmBNa-o0P5YYsKmsKO0Q.png" /></figure><p>GRPC is a RPC (Remote Procedure Call) framework that was released by Google in 2016. The <em>g</em> stands for “<em>great</em>” in the latest version(1.44) but in each version it stands for a different word (<a href="https://github.com/grpc/grpc/blob/master/doc/g_stands_for.md">https://github.com/grpc/grpc/blob/master/doc/g_stands_for.md</a>).</p><p>It can work with a wide range of media formats such as JSON, XML, Protocol Buffer (Protobuf) and Etc. But Protobuf is a better choice because of performance, type checking and strong backwards compatibility.</p><p>Protobuf was developed by Google and it used for serialize data. It is an IDL (Interface Definition Language) and it used for defining messages (data structure) and services in a file with extension of ‘.proto’. There are a lot of code generators for it in different programming languages.</p><p>In the following part, you see a small gRPC+Protobuf+Kotlin program.In this demo, we define service and messages by Protobuf and then we compile the program to generate classes and data structures. Finally, after service implementation, we create gRPC server.</p><h3>1. Code section</h3><p>1.1. Using Protobuf to define messages and services:</p><p>We created a file with the name ‘student.proto’ in the project directory(src\main\proto). This code shows a service and messages definitions. Let’s understand this code line by line:</p><blockquote>The first line shows the Protobuf version marked by the syntax keyword.</blockquote><blockquote>The second line is optional. It generates a separate file for each root-level message.</blockquote><blockquote>Package keyword defines the path for auto-generated files. Proto package located in the target/generated-sources/protobuf/{Package value}</blockquote><blockquote>Use the service keyword to define services and the rpc keyword to define methods in the service.</blockquote><blockquote>To Define data structures or objects, Use the message keyword. Each field in each message has strict data types and different numbers. This number used to serialize and parse binary messages.</blockquote><pre>syntax = “proto3”;</pre><pre>option java_multiple_files = true;</pre><pre>Package me.test.grpc.student;</pre><pre>service StudentService{<br> rpc getStudent(StudentRequest) returns (StudentResponse);<br>}</pre><pre>message StudentRequest {<br> string id = 1;<br>}</pre><pre>message StudentResponse {<br> string id = 1;<br> string name = 2;<br> string username = 3;<br>}</pre><p>1.2. Add Maven dependencies and plugin to pom.xml</p><pre>&lt;<strong>plugin</strong>&gt;<br> &lt;<strong>groupId</strong>&gt;org.xolstice.maven.plugins&lt;/<strong>groupId</strong>&gt;<br> &lt;<strong>artifactId</strong>&gt;protobuf-maven-plugin&lt;/<strong>artifactId</strong>&gt;<br> &lt;<strong>version</strong>&gt;0.6.1&lt;/<strong>version</strong>&gt;<br> &lt;<strong>configuration</strong>&gt;<br> &lt;<strong>protocArtifact</strong>&gt;com.google.protobuf:protoc:3.19.1:exe:${os.detected.classifier}&lt;/<strong>protocArtifact</strong>&gt;<br> &lt;<strong>pluginId</strong>&gt;grpc-java&lt;/<strong>pluginId</strong>&gt;<br> &lt;<strong>pluginArtifact</strong>&gt;io.grpc:protoc-gen-grpc-java:1.43.2:exe:${os.detected.classifier}&lt;/<strong>pluginArtifact</strong>&gt;<br> &lt;/<strong>configuration</strong>&gt;<br> &lt;<strong>executions</strong>&gt;<br> &lt;<strong>execution</strong>&gt;<br> &lt;<strong>goals</strong>&gt;<br> &lt;<strong>goal</strong>&gt;compile&lt;/<strong>goal</strong>&gt;<br> &lt;<strong>goal</strong>&gt;compile-custom&lt;/<strong>goal</strong>&gt;<br> &lt;/<strong>goals</strong>&gt;<br> &lt;/<strong>execution</strong>&gt;<br> &lt;/<strong>executions</strong>&gt;<br>&lt;/<strong>plugin</strong>&gt;</pre><pre>&lt;<strong>extensions</strong>&gt;<br> &lt;<strong>extension</strong>&gt;<br> &lt;<strong>groupId</strong>&gt;kr.motd.maven&lt;/<strong>groupId</strong>&gt;<br> &lt;<strong>artifactId</strong>&gt;os-maven-plugin&lt;/<strong>artifactId</strong>&gt;<br> &lt;<strong>version</strong>&gt;${os-maven-plugin.version}&lt;/<strong>version</strong>&gt;<br> &lt;/<strong>extension</strong>&gt;<br>&lt;/<strong>extensions</strong>&gt;</pre><pre>&lt;<strong>dependency</strong>&gt;<br> &lt;<strong>groupId</strong>&gt;io.grpc&lt;/<strong>groupId</strong>&gt;<br> &lt;<strong>artifactId</strong>&gt;grpc-protobuf&lt;/<strong>artifactId</strong>&gt;<br> &lt;<strong>version</strong>&gt;1.43.2&lt;/<strong>version</strong>&gt;<br>&lt;/<strong>dependency</strong>&gt;<br>&lt;<strong>dependency</strong>&gt;<br> &lt;<strong>groupId</strong>&gt;io.grpc&lt;/<strong>groupId</strong>&gt;<br> &lt;<strong>artifactId</strong>&gt;grpc-stub&lt;/<strong>artifactId</strong>&gt;<br> &lt;<strong>version</strong>&gt;1.43.2&lt;/<strong>version</strong>&gt;<br>&lt;/<strong>dependency</strong>&gt;<br>&lt;<strong>dependency</strong>&gt;<br> &lt;<strong>groupId</strong>&gt;io.grpc&lt;/<strong>groupId</strong>&gt;<br> &lt;<strong>artifactId</strong>&gt;protoc-gen-grpc-kotlin&lt;/<strong>artifactId</strong>&gt;<br> &lt;<strong>version</strong>&gt;1.2.0&lt;/<strong>version</strong>&gt;<br> &lt;<strong>type</strong>&gt;pom&lt;/<strong>type</strong>&gt;<br>&lt;/<strong>dependency</strong>&gt;<br>&lt;<strong>dependency</strong>&gt;<br> &lt;<strong>groupId</strong>&gt;io.grpc&lt;/<strong>groupId</strong>&gt;<br> &lt;<strong>artifactId</strong>&gt;grpc-netty-shaded&lt;/<strong>artifactId</strong>&gt;<br> &lt;<strong>version</strong>&gt;1.43.2&lt;/<strong>version</strong>&gt;<br>&lt;/<strong>dependency</strong>&gt;</pre><p>1.3. Compile the project to generate related models and files. Never change these classes. These classes are located in this path (target/generated-sources/protobuf/java/me/test/grpc/student)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*yr3lG2siwCnjiVN5a4Q4gQ.png" /></figure><p>1.4. Implement service logic using auto-generated classes and models:</p><pre>class StudentServiceImp : StudentServiceImplBase() {</pre><pre> companion object {<br> private val logger = KotlinLogging.logger(“StudentServiceImp”)<br> }</pre><pre> override fun getStudent(<br> request: Student.StudentRequest?,<br> responseObserver: StreamObserver&lt;Student.StudentResponse&gt;?<br> ) {<br> logger.info(“server received {}”, request)<br> val response =Student.StudentResponse.newBuilder()<br> .setId(request?.id!!)<br> .setAge(30)<br> .setName(“tester”)<br> .build()<br> logger.info(“server responded {}”, response)<br> responseObserver?.onNext(response)<br> responseObserver?.onCompleted()<br> }<br>}</pre><p>1.5. Add gRPC server class:</p><pre>class GrpcServer(port: Int) {<br> private val server: Server<br> companion object {<br> private var grpcServer: GrpcServer? = null<br> fun start(port: Int) {<br> if (grpcServer == null) grpcServer = GrpcServer(port)<br> try {<br> grpcServer!!.server.start()<br> println(“GRPC server started”)<br> grpcServer!!.server.awaitTermination()<br> } catch (e: IOException) {<br> println(“Can not start GRPC server”)<br> }<br> }<br> }</pre><pre> init {<br> server = ServerBuilder.forPort(port)<br> .addService(StudentServiceImp())<br> .intercept(GrpcServerInterceptor())<br> .build()<br> }<br>}</pre><p>1.6. Start gRPC server in main function:</p><pre>fun main(args: Array&lt;String&gt;) {</pre><pre>GrpcServer.start(6565)</pre><pre>}</pre><p>1.7. Test the app by <a href="https://kreya.app/">Kreya</a>.</p><p>The full source code for this article can be found <a href="https://github.com/Azdy-dev/Kotlin-gRPC">here</a>.</p><p><strong>2. Advantages/Disadvantages of gRPC</strong></p><p><strong>2.1. The gRPC advantages :</strong></p><ul><li>Very efficient for inter-service communication with low latency</li><li>Uses binary protocols</li><li>Uses HTTP/2</li><li>Strictly defined interfaces and strongly typed</li><li>Useful to create polyglot(multi-language) services and inter-service communications in microservices architecture</li><li>Support different type of service calls(Unary, client streaming such as file uploading, server streaming such as file downloading, bidirectional streaming such as interactive search)</li><li>Built-in code generation:<strong> </strong>No need to implement controller classes like REST-based API and no need to implement the serialization.</li></ul><p><strong>2.2. The gRPC disadvantages:</strong></p><ul><li>A few tools to test and monitor</li><li>Limited support by browsers because of using HTTP/2</li><li>Not suitable for browser-based application</li><li>Hard to debug and view and edit request/response because of binary format</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf5296887856" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/the-grpc-and-protobuf-in-action-with-kotlin-cf5296887856">Protobuf and gRPC In Action With Kotlin</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>