<?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 Kubra Ozer on Medium]]></title>
        <description><![CDATA[Stories by Kubra Ozer on Medium]]></description>
        <link>https://medium.com/@kubra123ozer?source=rss-db6728cec22d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*w72Qud4nEBpgc4yW.jpg</url>
            <title>Stories by Kubra Ozer on Medium</title>
            <link>https://medium.com/@kubra123ozer?source=rss-db6728cec22d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 01:23:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kubra123ozer/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[Connections and Transactions — Spring Boot Hibernate All about @Transaction]]></title>
            <link>https://kubra123ozer.medium.com/connections-and-transactions-spring-boot-hibernate-all-about-transaction-8b05a3fb9704?source=rss-db6728cec22d------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b05a3fb9704</guid>
            <category><![CDATA[hibernate]]></category>
            <category><![CDATA[jpa]]></category>
            <category><![CDATA[transactions]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Kubra Ozer]]></dc:creator>
            <pubDate>Mon, 18 Jan 2021 10:03:37 GMT</pubDate>
            <atom:updated>2021-01-18T10:06:37.363Z</atom:updated>
            <content:encoded><![CDATA[<h3>Connections and Transactions — Spring Boot Hibernate All about @Transactional</h3><h3>Introduction</h3><figure><img alt="https://aishwaryavaishno.wordpress.com/2013/06/07/hibernate-persistent-context-and-objects-lifecycle/" src="https://cdn-images-1.medium.com/max/613/0*TmCD0Fr01-8WiqJz.png" /></figure><p>With this article, you are going to learn about transactions in spring boot application and how to use @Transactional annotation with declarative way.</p><p>I will follow the <a href="https://learning.oreilly.com/library/view/spring-boot-persistence/9781484256268/">Spring Boot Persistence Best Practices</a> book steps that is written by <a href="https://learning.oreilly.com/search/?query=author%3A%22Anghel%20Leonard%22&amp;sort=relevance&amp;highlight=true">Anghel Leonard</a>. And I will try to summarize and simplify the items of the specific section in this book.</p><p>Firstly, you need to know what is <strong>transaction </strong>in a database. <strong>Transaction is a logical unit that is independently executed for data retrieval or updates</strong>. So we should control programmatically transaction management and database connections. But Spring provide us a declarative way and handle this boilerplate code for us so that we can focus on our business logic.</p><pre>try { <br>    utx.begin(); <br>    businessLogic();<br>    utx.commit(); <br>} catch(Exception ex) { <br>    utx.rollback(); <br>    throw ex; <br>}<br>//There is no need this with @Transactional annotation</pre><h3><strong><em>When we should get database connection </em></strong>Acquisition ?</h3><p>Hibernate will acquire the database connection of a JDBC transaction right after the transaction starts. This can be performance penalty if we acquire a connection where there is no need to start database connection. So , firstly we should determine which place is about database connection and which place is about other business logic.</p><p>In Spring, a method annotated with @Transactional acquires the database connection immediately after it is called.</p><h3>When we should use Transactional ?</h3><p>To be honest before I researched how transaction mechanism works in hibernate , I had only used @Transactional annotation with readOnly property. That is just what I know about @Transactional and also I know that I should know something more :). Probably you know what means of @Transactional(readOnly=true). But how it exactly works ?</p><ul><li>Basically, If we use @Transactional(readOnly = true) to a method which is performing create or update operation then we will not have newly created or updated record into the database but we will have the response data. So what are the readOnly and readWrite mode?</li><li><strong>read- only mode: </strong>In this mode, the hydrated state is discarded from memory and only the entities are kept in the Persistence Context.</li><li><strong>read-write mode: </strong>In this mode, both the entity and its hydrated state are available in the Persistence Context. They are available during the Persistence Context (until the Persistence Context is closed) or until the entity is detached. Hibernate extracts the loaded state from the underlying JDBC ResultSet. It is called hydration. Hydrated and detached state is needed by <strong>dirty checking mechanism and optimistic locking mechanism </strong>to compare current entity state and loaded snapshot for update statements. To be simple in this article , I won’t detail this mechanisms. But you can look at the following links for details.</li></ul><p>(I totally recommend you to follow the <a href="https://vladmihalcea.com/">Vlad Mihalcea’s blogs</a> to learn how to implement JPA-Hibernate with good performance and how to optimize our existing application which have some performance-penalties.)</p><ul><li><a href="https://vladmihalcea.com/the-anatomy-of-hibernate-dirty-checking/">The anatomy of Hibernate dirty checking mechanism - Vlad Mihalcea</a></li><li><a href="https://vladmihalcea.com/how-to-prevent-optimisticlockexception-using-hibernate-versionless-optimistic-locking/">How to prevent OptimisticLockException with Hibernate versionless optimistic locking - Vlad Mihalcea</a></li></ul><blockquote><strong>Setting </strong>@Transactional(<strong>readOnly=true) for read-only data is a good optimization of performance since the hydrated/loaded state is discarded. This allows Spring to optimize the underlying data access layer operations.</strong></blockquote><p>There are two case which is needed to be careful when implement @Transactional. Sometimes this annotation can be ignored;</p><ul><li>If you add @Transactional to a private, protected, or package-protected method.</li><li>If you add @Transactional to a method defined in the same class as where it is invoked.</li></ul><pre><a href="http://twitter.com/Service">@Service</a><br>public class UserService {</pre><pre><a href="http://twitter.com/PersistenceContext">@</a>Autowired<br>private SampleRepository sampleRepository;<br>  <br>public User createUser(String name) {<br>    User newUser = new User(name);<br>    return this.saveUser(newUser); <br>    // self-invocation, You should call this transactional method from other class.<br>}</pre><pre><a href="http://twitter.com/Transactional">@Transactional</a><br>public User saveUser(User newUser) {<br>    sampleRepository.save(newUser);<br>    return newUser;<br>}</pre><pre>}</pre><p>By default Spring doesn’t support transactional-context. You need to determine explicitly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/14d2518f8f58d7d89e205c54a9886aa9/href">https://medium.com/media/14d2518f8f58d7d89e205c54a9886aa9/href</a></iframe><p>Okay, this example is for simple application and small logic. Be careful when using @Transactional annotation when it comes to your logic is getting complex.</p><h3><strong>Let’s talk about long-running versus short transactions:</strong></h3><p>The service-method is annotated with @Transactional(readOnly = true) to explicitly define the transactional-context boundaries.</p><pre>public void longRunningServiceMethod() <br>{    <br>    //Service-method start ...  <br>  <br>    longRunningMethod();    <br>    //Complex,long running method for real-life implementation. </pre><pre>    SampleEntity entity = sampleRepository.fetchByName(&quot;Vilad&quot;);       <br>    //Service-method done ...<br>}</pre><blockquote>So, what is happening here? Spring starts the transaction and acquires the database connection immediately, before starting to run the longRunningMethod() method. The database connection is opened right away and is ready to be used. But we don’t use it right away, we just keep it open! We run some other tasks before calling fetchByName() , which is before the first interaction with the database connection. With this scenerio we open a transaction and occupy the database unnecessarily.</blockquote><p>So It seems like we can solve this problem for such a case by moving @Transactional in repository interface.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b800a46b3b825ea7ae203a637ae85a9/href">https://medium.com/media/3b800a46b3b825ea7ae203a637ae85a9/href</a></iframe><p>It’s good practice to define the @Transactional(readOnly = true) annotation at the class level and only override it for read-write methods.</p><p>But what if we call more than one query-methods, can we achieve ACID for database operation with above example of repository class? For example , It is possible that after fetching some entities(findAllById) you may want to change some of these entity(deleteByName). In result you have two different transaction context. Calling these two method in same service method without @Transactional annotation , you will lose ACID properties. So you need to use @Transactional at service level.</p><blockquote><strong>@Transactional in my experience is most useful if you have a service method with multiple JPA calls, and you want them all to happen in a single DB transaction.</strong></blockquote><p>Other alternative is delaying connection acquisition to handle long-running method for performance boosting.</p><p>We can delay the connection acquisition via the following these two settings:</p><pre>spring.datasource.hikari.auto-commit=false</pre><pre>spring.jpa.properties.hibernate.connection.provider_disables_autocommit=true</pre><pre>public void longRunningServiceMethod() <br>{    <br>    //Service-method start ...  <br>  <br>    longRunningMethod();    <br>    //Complex,long running method for real-life implementation.</pre><pre>    SampleEntity entity = sampleRepository.fetchByName(&quot;Vilad&quot;);       <br>    //Service-method done ...<br>}</pre><p>So our longRunningMethod() which is called in the longRunningServiceMethod() is running without keeping a database connection. When it comes to sampleRepository.fetchByName then the connection happens until the end of the method. So you can use @Transactional at service level and keep safe your application for long-running methods and ACID properties.</p><h3><strong>Prepare your repository interfaces:</strong></h3><p>This steps is quoted from the book which is referred to in Introduction section:</p><ul><li>Annotate the repository interfaces with @Transactional(readOnly=true).</li><li>Override @Transactional(readOnly=true) with @Transactional for query-methods that modify data/generate DML (such as INSERT, UPDATE, and DELETE).</li><li>For Hibernate 5.2.10+, delay the database connection acquisition until it’s really needed</li><li>Evaluate each service-method to decide if it should be annotated with @Transactional or not.</li><li>If you decide to annotate a service-method with @Transactional then add the proper @Transactional. You should add</li><li>@Transactional(readOnly=true) if you call just read-only query-methods and add @Transactional if you call at least one query-method that can modify data.</li><li>Be sure to evaluate the transaction duration and behavior in the context of the current transaction propagation mechanism and strive for short and short/fast transactions.</li></ul><h3>References</h3><ul><li><a href="https://www.amazon.com/gp/product/B087WS81RK/ref=dbs_a_def_rwt_bibl_vppi_i3">Spring Boot Persistence Best Practices: Optimize Java Persistence Performance in Spring Boot Applications</a></li><li><a href="https://thorben-janssen.com/transactions-spring-data-jpa/">Managing Transactions with Spring and Spring Data JPA</a></li><li><a href="https://vladmihalcea.com/read-write-read-only-transaction-routing-spring/">Read-write and read-only transaction routing with Spring - Vlad Mihalcea</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b05a3fb9704" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot Unit Test Annotations with Junit 5 -Service Layer -doReturn() , whenReturn , @Before…]]></title>
            <link>https://kubra123ozer.medium.com/spring-boot-unit-test-annotations-with-junit-5-service-layer-doreturn-whenreturn-before-ce8e1546923?source=rss-db6728cec22d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce8e1546923</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[mockito]]></category>
            <category><![CDATA[junit]]></category>
            <dc:creator><![CDATA[Kubra Ozer]]></dc:creator>
            <pubDate>Thu, 15 Oct 2020 10:26:08 GMT</pubDate>
            <atom:updated>2020-10-15T10:26:08.434Z</atom:updated>
            <content:encoded><![CDATA[<h3>Spring Boot Unit Test Annotations with Junit 5 -Service Layer -doReturn , whenReturn , @Before, @Spy</h3><p>This article is all about unit test by using junit for service layer. I explained the controller layer unit test in my first article. You can see the following link, if you need.</p><p><a href="https://medium.com/@kubra123ozer/spring-boot-unit-test-annotations-with-junit-5-controller-25bb0384569b">Spring Boot Unit Test Annotations with Junit 5 -Controller</a></p><p>I will explain all method about unit test that is used in my code . Let’s get started.</p><p>Firstly, I want to show you some differences about methods that look as if they are same.</p><h3>Mockito: doReturn vs thenReturn</h3><p>These methods specify what to return when a method is called. In most cases , when-thenReturn is preferred because of readability. However, they have some differences</p><ul><li>doReturn is not type safety.Unlike the doReturn , thenReturn checks method return types and if there is an unsafe type , it raises compile error.</li><li>doReturn is no side effect. This is an advantage, although there is no type safety. If you use spied object that is annotated with @Spy doReturn doesn’t call the method at all .</li><li>thenReturn calls the real method and you need to handle exceptional case, you need to mock the throw maybe.</li><li>If there is no side effect you can use thenReturn for a spied object, although this can be risky . You need to be sure about that :)</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5847cec2aa04759873d423bc4b628cdd/href">https://medium.com/media/5847cec2aa04759873d423bc4b628cdd/href</a></iframe><h3>What about Spy ?</h3><p><strong>A spy in mockito is a partial mock</strong>. So If you use objects methods , it is a real method invocation for spied object. So as i mentioned above , this can cause some side effects</p><p>This link is good explanation about their differences and you can see the usage of doReturn in the example of that article.</p><p><a href="https://javapointers.com/java/unit-test/difference-between-spy-and-mock-in-mockito/">Difference between Spy and Mock in Mockito - JavaPointers</a></p><h3>@BeforeEach vs @BeforeAll</h3><p>Lastly, I want to tell you about <strong>@BeforeEach </strong>and <strong>@BeforeAll </strong>annotations. The method annotated with <strong>@BeforeEach</strong> is executed before each test , as it is name signifies :) . On the other side , <strong>@BeforeAll</strong> annotation provides runs once before the entire test class.</p><p>Generally , if multiple tests share same code you can use <strong>@BeforeAll</strong> (in Junit 4 @BeforeClass) .<strong><em>Establishing database connection can be example for this annotation</em></strong>. You can do some object initializations in the method that is annotated with <strong>@BeforeEach </strong>(in Junit 4 @Before ) , as you can see in my example code.</p><p>In addition , you can think same logic for <strong>@AfterEach </strong>and <strong>@AfterAll</strong>. This time , these method runs after the test execution :)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c61119f0dcaa7e33103edbcc1559352/href">https://medium.com/media/3c61119f0dcaa7e33103edbcc1559352/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/473/1*A5A0822K2DOo9dcU_RSimQ.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc37fa817807197e448e7078601a29ac/href">https://medium.com/media/bc37fa817807197e448e7078601a29ac/href</a></iframe><h3><strong>Conclusion</strong></h3><p>I explained the main differences about some unit test metrics that can cause some troubleshoots when we don’t know what exactly they mean ,as much as I can. I hope that will helpful for you.</p><p>Thank you for your reading :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce8e1546923" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot Unit Test Annotations with Junit 5 -Controller]]></title>
            <link>https://kubra123ozer.medium.com/spring-boot-unit-test-annotations-with-junit-5-controller-25bb0384569b?source=rss-db6728cec22d------2</link>
            <guid isPermaLink="false">https://medium.com/p/25bb0384569b</guid>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[junit-5]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[unit-test-framework]]></category>
            <dc:creator><![CDATA[Kubra Ozer]]></dc:creator>
            <pubDate>Thu, 17 Sep 2020 13:49:54 GMT</pubDate>
            <atom:updated>2020-09-17T13:53:17.199Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Spring Boot Unit Test Annotations with Junit 5 -Controller Layer</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*8Z9tsees6KsZLmJS" /><figcaption>Picture 1</figcaption></figure><p>Hi everybody, we will examine the unit test in spring boot by using Junit . I will cover for all layer (controller,service,repository)</p><p>As we know , all of you can write unit test easily because of the simplicity of unit test approaches. But most of us don’t use the all stuff consciously ,especially unit test annotations. But sometimes this can be critical .(performance issues etc.)</p><p><strong>So ,lets get started , i can’t wait :)</strong></p><p>First of all , i used my demo project to implement the unit test from my github account. If you want to look into details for the project , you can visit my repository:</p><p><a href="https://github.com/kbra95/recruitment-demo">kbra95/recruitment-demo</a></p><p>I guess i need to say our dependencies for our test implementation :)</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;<br>   &lt;scope&gt;test&lt;/scope&gt;<br>   &lt;version&gt;${spring.boot.test.version}&lt;/version&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;com.h2database&lt;/groupId&gt;<br>    &lt;artifactId&gt;h2&lt;/artifactId&gt;<br>    &lt;scope&gt;test&lt;/scope&gt;<br>&lt;/dependency&gt;</pre><p>Spring-boot-starter-test is primary dependency that satisfy the main test stuff requirements. H2 embedded database is required so that it eliminates the database configurations for actual database.</p><ul><li><strong>@SpringBootTest: </strong>It can be used as an alternative to the standard @ContextConfiguration.This annotation creates the ApplicationContext used in your tests.</li><li><strong>@ExtendWith : </strong>Developers can register one or more extensions declaratively by annotating a test interface, test class, test method, or custom composed annotation with @ExtendWith(…​) and supplying class references for the extensions to register.</li><li><strong>SpringExtension</strong> integrates the Spring TestContext Framework into JUnit 5’s Jupiter programming model.</li><li><strong>@AutoConfigureMockMvc: </strong>Annotation that can be applied to a test class to enable and configure auto-configuration of <a href="https://docs.spring.io/spring-framework/docs/5.2.8.RELEASE/javadoc-api/org/springframework/test/web/servlet/MockMvc.html?is-external=true">MockMvc</a>. Use AutoConfigureWebMvc if you need to configure the web layer for testing but don’t need to use MockMvc. When you just want to configure mockMvc, then use the AutoConfigureWebMvc.</li></ul><p><strong>These annotations are class level annotations , when you have done this part so let’s start inside of the our test class.</strong></p><pre>@ExtendWith(SpringExtension.<strong>class</strong>)<br>@SpringBootTest<br>@AutoConfigureMockMvc<br><strong>public class </strong>InterviewControllerTest {<br>...</pre><p><strong>@MockBean Vs @Mock : </strong>Spring boot @MockBean annotation used to add mocks to a Spring ApplicationContext. This class is included in the spring-boot-test,but @Mock annotation is Mockito library’s mock.</p><p>As we write a test that doesn’t need any dependencies from the Spring Boot container, the <a href="https://howtodoinjava.com/mockito/junit-mockito-example/">Mockito</a>‘s @Mock shall be used.</p><p>Note that to enable Mockito annotations during test executions, the MockitoAnnotations.initMocks(this) static method has to be called.It is fast and favors the isolation of the tested component.</p><p>If the test needs to rely on the Spring Boot container and we want also to add or mock one of the container beans then @MockBean from Spring Boot is preferred way to add mocks.We generally use @MockBean along with @WebMvcTest</p><p>If you totally understand what mean of these annotations, so you can examine my code snippet .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b62e1fdd86433054d4d27732c72a1c00/href">https://medium.com/media/b62e1fdd86433054d4d27732c72a1c00/href</a></iframe><p>Note that this test class is supposed to be improved , we need to cover all test case in the real project so that the errors are reduced in production release. This article is partitioned,for example ; Part 2 will cover Service tests, Part 3 will cover repository tests.</p><p>If this article is helpful for you, you can follow me and please wait for other articles :)</p><p>Here, some useful links for you :</p><ul><li><a href="https://howtodoinjava.com/spring-boot2/testing/spring-mockbean-annotation">Spring boot @MockBean Example - HowToDoInJava</a></li><li><a href="https://junit.org/junit5/docs/current/user-guide/#extensions">JUnit 5 User Guide</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25bb0384569b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>