<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Sohail Shah</title>
    <description>The latest articles on Forem by Sohail Shah (@sohailshah).</description>
    <link>https://forem.com/sohailshah</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F784054%2F72b85092-809a-4b5a-a330-1282eb2a8d1e.jpg</url>
      <title>Forem: Sohail Shah</title>
      <link>https://forem.com/sohailshah</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/sohailshah"/>
    <language>en</language>
    <item>
      <title>Create Persistence Unit Without The persistence.xml file</title>
      <dc:creator>Sohail Shah</dc:creator>
      <pubDate>Tue, 12 Sep 2023 13:41:47 +0000</pubDate>
      <link>https://forem.com/sohailshah/create-persistence-unit-without-the-persistencexml-file-3lh8</link>
      <guid>https://forem.com/sohailshah/create-persistence-unit-without-the-persistencexml-file-3lh8</guid>
      <description>&lt;p&gt;When working with JPA with Java applications, we usually create a persistence unit in the persistence.xml file as below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight xml"&gt;&lt;code&gt;&lt;span class="cp"&gt;&amp;lt;?xml version="1.0" encoding="UTF-8"?&amp;gt;&lt;/span&gt;
&lt;span class="nt"&gt;&amp;lt;persistence&lt;/span&gt; &lt;span class="na"&gt;xmlns=&lt;/span&gt;&lt;span class="s"&gt;"http://java.sun.com/xml/ns/persistence"&lt;/span&gt;
             &lt;span class="na"&gt;xmlns:xsi=&lt;/span&gt;&lt;span class="s"&gt;"http://www.w3.org/2001/XMLSchema-instance"&lt;/span&gt;
             &lt;span class="na"&gt;xsi:schemaLocation=&lt;/span&gt;&lt;span class="s"&gt;"http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"&lt;/span&gt;
             &lt;span class="na"&gt;version=&lt;/span&gt;&lt;span class="s"&gt;"2.0"&lt;/span&gt;&lt;span class="nt"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="nt"&gt;&amp;lt;persistence-unit&lt;/span&gt; &lt;span class="na"&gt;name=&lt;/span&gt;&lt;span class="s"&gt;"myPersistenceUnit"&lt;/span&gt; &lt;span class="na"&gt;transaction-type=&lt;/span&gt;&lt;span class="s"&gt;"RESOURCE_LOCAL"&lt;/span&gt;&lt;span class="nt"&gt;&amp;gt;&lt;/span&gt;
        &lt;span class="nt"&gt;&amp;lt;description&amp;gt;&lt;/span&gt;persistence unit description&lt;span class="nt"&gt;&amp;lt;/description&amp;gt;&lt;/span&gt;
        &lt;span class="nt"&gt;&amp;lt;provider&amp;gt;&lt;/span&gt;org.hibernate.jpa.HibernatePersistenceProvider&lt;span class="nt"&gt;&amp;lt;/provider&amp;gt;&lt;/span&gt;
        &lt;span class="nt"&gt;&amp;lt;exclude-unlisted-classes&amp;gt;&lt;/span&gt;false&lt;span class="nt"&gt;&amp;lt;/exclude-unlisted-classes&amp;gt;&lt;/span&gt;
        &lt;span class="nt"&gt;&amp;lt;properties&amp;gt;&lt;/span&gt;
            &lt;span class="c"&gt;&amp;lt;!-- Database connection properties --&amp;gt;&lt;/span&gt;
            &lt;span class="nt"&gt;&amp;lt;property&lt;/span&gt; &lt;span class="na"&gt;name=&lt;/span&gt;&lt;span class="s"&gt;"javax.persistence.jdbc.url"&lt;/span&gt; &lt;span class="na"&gt;value=&lt;/span&gt;&lt;span class="s"&gt;"jdbc:h2:tcp://localhost/~/test"&lt;/span&gt;&lt;span class="nt"&gt;/&amp;gt;&lt;/span&gt;
            &lt;span class="nt"&gt;&amp;lt;property&lt;/span&gt; &lt;span class="na"&gt;name=&lt;/span&gt;&lt;span class="s"&gt;"javax.persistence.jdbc.driver"&lt;/span&gt; &lt;span class="na"&gt;value=&lt;/span&gt;&lt;span class="s"&gt;"org.h2.Driver"&lt;/span&gt;&lt;span class="nt"&gt;/&amp;gt;&lt;/span&gt;
            &lt;span class="nt"&gt;&amp;lt;property&lt;/span&gt; &lt;span class="na"&gt;name=&lt;/span&gt;&lt;span class="s"&gt;"javax.persistence.jdbc.user"&lt;/span&gt; &lt;span class="na"&gt;value=&lt;/span&gt;&lt;span class="s"&gt;"sa"&lt;/span&gt;&lt;span class="nt"&gt;/&amp;gt;&lt;/span&gt;
            &lt;span class="nt"&gt;&amp;lt;property&lt;/span&gt; &lt;span class="na"&gt;name=&lt;/span&gt;&lt;span class="s"&gt;"javax.persistence.jdbc.password"&lt;/span&gt; &lt;span class="na"&gt;value=&lt;/span&gt;&lt;span class="s"&gt;""&lt;/span&gt;&lt;span class="nt"&gt;/&amp;gt;&lt;/span&gt;

            &lt;span class="c"&gt;&amp;lt;!-- Hibernate properties --&amp;gt;&lt;/span&gt;
            &lt;span class="nt"&gt;&amp;lt;property&lt;/span&gt; &lt;span class="na"&gt;name=&lt;/span&gt;&lt;span class="s"&gt;"hibernate.dialect"&lt;/span&gt; &lt;span class="na"&gt;value=&lt;/span&gt;&lt;span class="s"&gt;"org.hibernate.dialect.H2Dialect"&lt;/span&gt;&lt;span class="nt"&gt;/&amp;gt;&lt;/span&gt;
            &lt;span class="nt"&gt;&amp;lt;property&lt;/span&gt; &lt;span class="na"&gt;name=&lt;/span&gt;&lt;span class="s"&gt;"hibernate.show_sql"&lt;/span&gt; &lt;span class="na"&gt;value=&lt;/span&gt;&lt;span class="s"&gt;"true"&lt;/span&gt;&lt;span class="nt"&gt;/&amp;gt;&lt;/span&gt;
            &lt;span class="nt"&gt;&amp;lt;property&lt;/span&gt; &lt;span class="na"&gt;name=&lt;/span&gt;&lt;span class="s"&gt;"hibernate.format_sql"&lt;/span&gt; &lt;span class="na"&gt;value=&lt;/span&gt;&lt;span class="s"&gt;"true"&lt;/span&gt;&lt;span class="nt"&gt;/&amp;gt;&lt;/span&gt;
            &lt;span class="nt"&gt;&amp;lt;property&lt;/span&gt; &lt;span class="na"&gt;name=&lt;/span&gt;&lt;span class="s"&gt;"hibernate.hbm2ddl.auto"&lt;/span&gt; &lt;span class="na"&gt;value=&lt;/span&gt;&lt;span class="s"&gt;"create"&lt;/span&gt;&lt;span class="nt"&gt;/&amp;gt;&lt;/span&gt;
        &lt;span class="nt"&gt;&amp;lt;/properties&amp;gt;&lt;/span&gt;
    &lt;span class="nt"&gt;&amp;lt;/persistence-unit&amp;gt;&lt;/span&gt;
&lt;span class="nt"&gt;&amp;lt;/persistence&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The persistence unit can also be created programmatically without creating an XML file. &lt;/p&gt;

&lt;p&gt;The persistence unit is created as a Java class which represents all the properties present in the XML file. This class must implement the interface &lt;strong&gt;PersistenceUnitInfo&lt;/strong&gt; which defines the contact that needs to be fulfilled in order to create the persistence unit.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;MyPersistenceUnit&lt;/span&gt; &lt;span class="kd"&gt;implements&lt;/span&gt; &lt;span class="nc"&gt;PersistenceUnitInfo&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="nd"&gt;@Override&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="nf"&gt;getPersistenceUnitName&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="nd"&gt;@Override&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="nf"&gt;getPersistenceProviderClassName&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="nd"&gt;@Override&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;PersistenceUnitTransactionType&lt;/span&gt; &lt;span class="nf"&gt;getTransactionType&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="nd"&gt;@Override&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;DataSource&lt;/span&gt; &lt;span class="nf"&gt;getJtaDataSource&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="nd"&gt;@Override&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;DataSource&lt;/span&gt; &lt;span class="nf"&gt;getNonJtaDataSource&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="nd"&gt;@Override&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;getMappingFileNames&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="nd"&gt;@Override&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="no"&gt;URL&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;getJarFileUrls&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="nd"&gt;@Override&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="no"&gt;URL&lt;/span&gt; &lt;span class="nf"&gt;getPersistenceUnitRootUrl&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="nd"&gt;@Override&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;getManagedClassNames&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="nd"&gt;@Override&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;boolean&lt;/span&gt; &lt;span class="nf"&gt;excludeUnlistedClasses&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;false&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="nd"&gt;@Override&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;SharedCacheMode&lt;/span&gt; &lt;span class="nf"&gt;getSharedCacheMode&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="nd"&gt;@Override&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;ValidationMode&lt;/span&gt; &lt;span class="nf"&gt;getValidationMode&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="nd"&gt;@Override&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;Properties&lt;/span&gt; &lt;span class="nf"&gt;getProperties&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="nd"&gt;@Override&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="nf"&gt;getPersistenceXMLSchemaVersion&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="nd"&gt;@Override&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;ClassLoader&lt;/span&gt; &lt;span class="nf"&gt;getClassLoader&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="nd"&gt;@Override&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;addTransformer&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;ClassTransformer&lt;/span&gt; &lt;span class="n"&gt;classTransformer&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;

    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="nd"&gt;@Override&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;ClassLoader&lt;/span&gt; &lt;span class="nf"&gt;getNewTempClassLoader&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;All the properties present in the XML file are provided by overriding the methods of the &lt;strong&gt;PersistenceUnitInfo&lt;/strong&gt; interface.&lt;/p&gt;

&lt;h3&gt;
  
  
  Persistence Unit Name
&lt;/h3&gt;

&lt;p&gt;Every persistence unit must have a name, that's because there can be more than one persistence unit in a project but it is rare to have more than one.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Override&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="nf"&gt;getPersistenceUnitName&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="s"&gt;"mypersistenceUnit"&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Persistence Provider Class Name
&lt;/h3&gt;

&lt;p&gt;It is the JPA implementation provider that needs to be defined in the persistence unit. In my case it is Hibernate.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Override&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="nf"&gt;getPersistenceProviderClassName&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="s"&gt;"org.hibernate.jpa.HibernatePersistenceProvider"&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Transaction Type
&lt;/h3&gt;

&lt;p&gt;The persistence unit must also provide the transaction type it is going to use. Depending on the type of application transaction type is decided&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Override&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;PersistenceUnitTransactionType&lt;/span&gt; &lt;span class="nf"&gt;getTransactionType&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nc"&gt;PersistenceUnitTransactionType&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;RESOURCE_LOCAL&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  DataSource
&lt;/h3&gt;

&lt;p&gt;For JPA to establish a connection to the database, it needs a data source object containing database credentials. In the XML file, we didn't need to define any data source, it automatically created one using some internal implementation. But in the Java class, it needs to be defined manually. The best way to create a data source is using a Hikari Data source object. &lt;br&gt;
Add the Hikari dependency in the pom.xml file&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight xml"&gt;&lt;code&gt;&lt;span class="nt"&gt;&amp;lt;dependency&amp;gt;&lt;/span&gt;
    &lt;span class="nt"&gt;&amp;lt;groupId&amp;gt;&lt;/span&gt;com.zaxxer&lt;span class="nt"&gt;&amp;lt;/groupId&amp;gt;&lt;/span&gt;
    &lt;span class="nt"&gt;&amp;lt;artifactId&amp;gt;&lt;/span&gt;HikariCP&lt;span class="nt"&gt;&amp;lt;/artifactId&amp;gt;&lt;/span&gt;
    &lt;span class="nt"&gt;&amp;lt;version&amp;gt;&lt;/span&gt;5.0.1&lt;span class="nt"&gt;&amp;lt;/version&amp;gt;&lt;/span&gt;
&lt;span class="nt"&gt;&amp;lt;/dependency&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now create the Datasource object and return it&lt;br&gt;
&lt;br&gt;
 &lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Override&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;DataSource&lt;/span&gt; &lt;span class="nf"&gt;getJtaDataSource&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="nc"&gt;HikariDataSource&lt;/span&gt; &lt;span class="n"&gt;dataSource&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;HikariDataSource&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
    &lt;span class="n"&gt;dataSource&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setJdbcUrl&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"database-utl"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
    &lt;span class="n"&gt;dataSource&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setUsername&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"username"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
    &lt;span class="n"&gt;dataSource&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setPassword&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"password"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;dataSource&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h3&gt;
  
  
  Managed Classes
&lt;/h3&gt;

&lt;p&gt;When using the XML file, the entities' objects were automatically registered and managed by the JPA. In the Java file, you need to define all the entity classes that need to be managed by the JPA.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Override&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;getManagedClassNames&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nc"&gt;List&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;of&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"org.com.model.Student"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It may or may not work even if you didn't define the entities in the file.&lt;br&gt;
These are the minimum required configuration you need to run the application with JPA.&lt;/p&gt;

&lt;p&gt;When using the XML file, &lt;strong&gt;EntityManagerFactory&lt;/strong&gt; is created by passing the persistence unit name in the constructor.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;EntityManagerFactory&lt;/span&gt; &lt;span class="n"&gt;entityManagerFactory&lt;/span&gt; 
            &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Persistence&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;createEntityManagerFactory&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"myPersistenceUnit"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To create an &lt;strong&gt;EntityManagerFactory&lt;/strong&gt; with the Java class implementation, we do this&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;EntityManagerFactory&lt;/span&gt; &lt;span class="n"&gt;entityManagerFactory&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
      &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nf"&gt;HibernatePersistenceProvider&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt;
        &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;createContainerEntityManagerFactory&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;MyPersistenceUnit&lt;/span&gt;&lt;span class="o"&gt;(),&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;HashMap&lt;/span&gt;&lt;span class="o"&gt;());&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The hashmap is used to pass properties, I have passed an empty hashmap here since we don't have any properties to pass.&lt;br&gt;
Using the entity manager factory, an entity manager can be created as it is done normally.&lt;/p&gt;

&lt;p&gt;Although the persistence unit class doesn't provide any performance benefits of kind over the use of persistence.xml file, the choice of which to use is purely based on one's personal preference. Maybe in your next project, if you don't want to deal with any XML files try creating your own persistence unit class.&lt;/p&gt;

</description>
      <category>java</category>
      <category>hibernate</category>
      <category>spring</category>
      <category>persistence</category>
    </item>
    <item>
      <title>OAuth 2.0 Simplified: Know What You Need To Begin</title>
      <dc:creator>Sohail Shah</dc:creator>
      <pubDate>Tue, 29 Aug 2023 13:42:10 +0000</pubDate>
      <link>https://forem.com/sohailshah/oauth-20-simplified-know-what-you-need-to-begin-m8c</link>
      <guid>https://forem.com/sohailshah/oauth-20-simplified-know-what-you-need-to-begin-m8c</guid>
      <description>&lt;p&gt;If you are a professional developer or someone who is starting out, you might have come across OAuth 2.0. You might have tried to learn more about it but found it a bit tricky to understand. That's okay because OAuth 2.0 can be a bit like a puzzle with various pieces involving technical terms and processes that might seem overwhelming&lt;/p&gt;

&lt;p&gt;In this post, I'll try to go through the core concepts of OAuth 2.0 that will provide you with a strong foundation. We'll focus on the essential building blocks that form the basis of this authorization protocol. &lt;/p&gt;

&lt;p&gt;Before we get started it is important to remember that OAuth 2.0 is a specification and does not provide any concrete implementation. Keeping that in mind let's get started.&lt;/p&gt;

&lt;p&gt;In the OAuth 2.0 specification, there are 4 main actors or roles.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Resource owner&lt;/strong&gt; - It is the user who is trying to access a resource&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Client&lt;/strong&gt; - The client can be the browser, mobile app, desktop app, or any other application.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Resource Server&lt;/strong&gt; - It is simply the backend of an application that hosts the protected resources(APIs). The user can access the resources on the backend through a client using a request protocol like HTTP using access tokens.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Authorization Server&lt;/strong&gt;- The server that issues access token to the client after successful authentication. Using the access token, protected resources on the resource server can be accessed by the user through the client.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--txTcHT4p--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/24q5d7xaee2ozjuwmpqo.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--txTcHT4p--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/24q5d7xaee2ozjuwmpqo.png" alt="Image description" width="800" height="234"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Authorization Grant
&lt;/h2&gt;

&lt;p&gt;Authorization Grant is a credential that gives that client authorization to obtain access token from the Authorization Server. There are a few grant types but we'll discuss following the types because these are the recommended ones to use.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Authorization Code &lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Client Credential &lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Refresh Token&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  Authorization Code
&lt;/h3&gt;

&lt;p&gt;After a user successfully authenticates itself with the authorization server, the authorization server sends the client an authorization code. The authorization code is kind of a key or a secret. The client can now make a POST request using this authorization code and get an access token back. It is important that the client itself should authenticate with the authorization server when making the request.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--xUt9hhCB--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/91oem5w8l28eemr1rkii.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--xUt9hhCB--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/91oem5w8l28eemr1rkii.png" alt="Image description" width="800" height="737"&gt;&lt;/a&gt;&lt;br&gt;
The above shows the typical flow for grant type of Authoziraztion Code.&lt;/p&gt;

&lt;p&gt;Points to remember:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;When the user is not logged in and tries to perform an action on a specific URL, the user is redirected to the login, and the same URL is passed to the Authorization.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For example, a user tries to comment on a post on Reddit on the URL &lt;strong&gt;&lt;em&gt;reddit.com/r/java/post10&lt;/em&gt;&lt;/strong&gt;. The user is redirected to the login page and the same URL is passed to the authorization server. After entering the user credentials and completing the flow to get the access token, the user is again redirected to the &lt;strong&gt;&lt;em&gt;reddit.com/r/java/post10&lt;/em&gt;&lt;/strong&gt; URL.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The login page is not provided by the client (front-end application) but by the Authorization Server itself.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For example, when you log in to Reddit and select Google to log in. The login page to select Google account is provided by Google, not Reddit. The same goes for other OAuth 2.0 login providers like Github, Facebook, Apple, etc. &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;A user's login credentials are never shared with the client. The login credentials are directly processed by the Authorization Server.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;After successful user authentication, the Authorization Server sends the client Authorization Code. The Authorization Code can be used only once by the client to get access token. It doesn't matter whether the request by the client was successful or not, once the Authorization Code is consumed by the Authorization Server it cannot be used anymore.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;When the client makes the POST request to get access token, the client itself has to authenticate with Authentication Server by using some kind of authentication mechanism like Http Baisc. &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The Authorization Server manages both the user credentials and the client credentials. The user credentials are usually username and password. The client credentials are clientId and secret.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;
  
  
  Authorization Code With PKCE
&lt;/h3&gt;

&lt;p&gt;PKCE stands for "proof Key for Code Exchange". It is an extension to OAuth 2.0 for native client applications which store the client credentials in the application itself. The client credentials can be compromised when it resides in the codebase of native applications like mobile apps. In web apps, the client credentials are safe enough as the code is present on the server that is not accessible to the public. But it is recommended to use PCKE even for web apps because your applications can never be safe enough.&lt;/p&gt;

&lt;p&gt;Two things we need to know when dealing with PKCE is verifier and challenge. The verifier can be a random piece of string, or code and the challenger is a hash value of the verifier&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="n"&gt;verifier&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"random string code"&lt;/span&gt;
&lt;span class="n"&gt;challenge&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;hash&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;verifier&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's see the steps involved &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;When the user is redirected to the login page, the client application generates the verifier and the challenge.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The challenge is sent to the Authorization Server along with user credentials for authentication request.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;After successful authentication and getting the Authorization Code, the client makes the request to get the access token, and instead of sending the client credentials along with the request the client sends the verifier to the Authorization Server.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The Authorization Server that already has the challenge now can validate if the verifier is indeed the same as the challenge by using the hash function matches.&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="c1"&gt;//Authorization Server has the challenge already &lt;/span&gt;
&lt;span class="n"&gt;tempChallenge&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;hash&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;verifier&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;tempChallenge&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;equals&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;challenge&lt;/span&gt;&lt;span class="o"&gt;))&lt;/span&gt;
&lt;span class="c1"&gt;//If it is equal, client validation is successful and access token is genereated&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--fPurv9aJ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/obbo6j208eao9leygc9c.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--fPurv9aJ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/obbo6j208eao9leygc9c.png" alt="Image description" width="800" height="737"&gt;&lt;/a&gt;&lt;br&gt;
Points to remember:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;The verifier never leaves the client, so it is never exposed to the public.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The hash function and the algorithm used by the function is only known by the client and Authorization Server.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Client Credentials
&lt;/h3&gt;

&lt;p&gt;In situations where there is no user, the client acts on its own behalf and can request access to resources on the Resource Server. For example, services in a microservice, monitoring tools, and orchestration tools like Kubernetes can request access to resources from a Resource Server. Since there is no user here, they act like a client and need client credentials to be validated by the Authorization Server to get a token. Only then using the tokens these clients can access the protected resources.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--5rJoShaF--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6gezh30f45z5w1ahv4x6.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--5rJoShaF--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6gezh30f45z5w1ahv4x6.png" alt="Image description" width="800" height="937"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Refresh Token
&lt;/h3&gt;

&lt;p&gt;We have already seen the flow for getting an access token after the user has been authenticated. The access token always expires after a prescribed amount of time then the user has to log in to get the access token again. Instead of the user logging in again, a refresh token is used to get the access token. This client is configured such that once the access token expires, it uses the access token to get a new access token and the refresh token. This happens without the user ever knowing.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--AhOxw_DJ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7a1ofqxptbxud9tfqjb0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--AhOxw_DJ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7a1ofqxptbxud9tfqjb0.png" alt="Image description" width="800" height="593"&gt;&lt;/a&gt;&lt;br&gt;
These are the basic building blocks that you can use to create your own Oauth 2.0 authorization mechanism using any popular OAuth 2.0 provider like OpenID Connect(OIDC) or Keycloak. There are many other providers available and you can easily work with any of them if you have understood the basics fundamentals we have discussed in this post.&lt;/p&gt;

&lt;p&gt;In the next post, we'll implement OAuth 2.0 with OIDC as an implementation provider using Spring Boot and check out some endpoints we need to know to validate and generate different tokens. So make sure to follow and leave a like on this post.&lt;/p&gt;

</description>
      <category>oauth</category>
      <category>springboot</category>
      <category>java</category>
    </item>
    <item>
      <title>Using Optional in Java the right way</title>
      <dc:creator>Sohail Shah</dc:creator>
      <pubDate>Mon, 21 Aug 2023 13:22:13 +0000</pubDate>
      <link>https://forem.com/sohailshah/using-optionals-in-java-the-right-way-4aho</link>
      <guid>https://forem.com/sohailshah/using-optionals-in-java-the-right-way-4aho</guid>
      <description>&lt;p&gt;It doesn't matter how much time you have been programming, &lt;strong&gt;NullPointerException&lt;/strong&gt; is one of the most frustrating problems you'll face.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fae4m27q8lduyltpxwrka.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fae4m27q8lduyltpxwrka.png" alt="Image description"&gt;&lt;/a&gt;&lt;br&gt;
The Optional class was introduced in Java 8 to tackle the problem of &lt;strong&gt;&lt;em&gt;NullPointerException&lt;/em&gt;&lt;/strong&gt;'s.&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;java.util.Optional&lt;/strong&gt; class is a generic type class that contains only one value of type &lt;strong&gt;T&lt;/strong&gt;. Its purpose is to provide a safer alternative to reference objects of a type T that can be null. But optional objects are safe only when used the right way. &lt;/p&gt;

&lt;p&gt;Let's see the ways you can create optional objects&lt;/p&gt;

&lt;h3&gt;
  
  
  Empty Optional
&lt;/h3&gt;

&lt;p&gt;Using the &lt;strong&gt;Optional.empty()&lt;/strong&gt; we can create an optional object which is empty of any type&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
 Java
//returning a empty optional of type string
public static Optional&amp;lt;String&amp;gt; emptyOptional(){
       return Optional.empty();
    } 

//or
Optional&amp;lt;String&amp;gt; str = Optional.empty();


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h3&gt;
  
  
  Nullable Optional
&lt;/h3&gt;

&lt;p&gt;Using the &lt;strong&gt;Optional.ofNullable()&lt;/strong&gt; method we can create nullable optional objects. These objects can be null or have values in them&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
 Java
public static Optional&amp;lt;Wallet&amp;gt; getWallet(){
        return Optional.ofNullable(null);
    }


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h3&gt;
  
  
  Non-Nullable Optional
&lt;/h3&gt;

&lt;p&gt;Using the &lt;strong&gt;Optional.of()&lt;/strong&gt; method we can create non-nullable optional objects.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
 Java
public static Optional&amp;lt;Wallet&amp;gt; getWallet(){
        return Optional.of(new Wallet(100));
    }


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now let's look at different methods present in the Optional class that we can leverage to write clean code promoting null safety.&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;get()&lt;/strong&gt; method in the optional class gets the value if it exists or throws a &lt;strong&gt;NoSuchElementException&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;For example, let's say we have an object &lt;strong&gt;Wallet&lt;/strong&gt; with private filed money. To get the money value we can do as below&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
 Java
//normal way to get money 
int savings = wallet.getMoney();

//when wallet object is wrapped in a optional 
int savings = optionalWallet.get().getMoney();


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;If the wallet object is null the second way is safer than the first way as it thorws &lt;strong&gt;NoSuchElementException&lt;/strong&gt; instead of &lt;strong&gt;NullPointerException&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We can improve the second way by using the &lt;strong&gt;isPresent()&lt;/strong&gt; method which returns a boolean for whether the value is present or not.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
 Java
List&amp;lt;Integer&amp;gt; savings = new ArrayList();
if(optionalWallet.isPresent()){
    savings.add(optionalWallet.get().getMoney());
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;But at the same time, this way of doing is not less verbose than checking for not null.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
 Java
List&amp;lt;Integer&amp;gt; savings = new ArrayList();
if(wallet != null){
  savings .add(wallet.getMoney());
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;To make the code more concise and clear, we can use &lt;strong&gt;ifPresent()&lt;/strong&gt; method which takes a consumer or a runnable, or both. Using &lt;strong&gt;ifPresent()&lt;/strong&gt; we can either consume a correct value or produce an alternative. Let's see how&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
 Java
List&amp;lt;Integer&amp;gt; savings = new ArrayList();
optionalWallet.ifPresent(wallet -&amp;gt; savings.add(wallet.getMoney()));


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;In the above example, money is added to savings only when the wallet is not null i.e., when it is present.&lt;/p&gt;

&lt;p&gt;In case we were adding the wallet itself to the list&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
 Java
//using lambda
List&amp;lt;Wallet&amp;gt; wallets  = new ArrayList&amp;lt;&amp;gt;();
optionalWallet.ifPresent(wallet -&amp;gt; wallets.add(wallet));

//you can also use method reference
List&amp;lt;Wallet&amp;gt; wallets  = new ArrayList&amp;lt;&amp;gt;();
optionalWallet.ifPresent(wallets::add);


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;As you can see it is much better than the examples in the beginning.&lt;/p&gt;

&lt;p&gt;There can be some scenarios where you might want to have a default value when the optional is empty, using the &lt;strong&gt;orElse()&lt;/strong&gt; method we can produce an alternative value when the optional is null. Let's see an example&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
 Java
List&amp;lt;Wallet&amp;gt; wallets  = new ArrayList&amp;lt;&amp;gt;();
Wallet wallet = optionalWallet.orElse(new Wallet(0));
wallets.add(wallet);


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;In the above example, if the optionalWallet contains a value it is assigned to the wallet variable if not a default wallet with value 0 is assigned. The &lt;strong&gt;orElse()&lt;/strong&gt; method can be used with any other type to produce default values.&lt;/p&gt;

&lt;p&gt;You can also invoke a block of code inside the &lt;strong&gt;orElseGet()&lt;/strong&gt; method to calculate a default value&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
 Java
//calculating a default value 
Wallet wallet = optionalWallet.orElseGet(() -&amp;gt; {
            int randomAmount = (int) (Math.random() * 500); // Generating a random amount between 0 and 500
            return new Wallet(randomAmount);
});


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;When working with spring boot applications and a database, when we make a select query to get a user, it is a good practice to wrap the user object around an optional, then we can do something like this&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
 Java
//Getting the user from database
Optional&amp;lt;User&amp;gt; findUserById(String id);

//Calling the find user method 
User user = findUserById(id)
                    .orElseThrow(UserNotFoundException::new);


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;In the above example, you can see, we didn't have to do any checks whether the user is not or not. If the user is present in the database we'll get the user, if not we gracefully throw an exception then and there itself.&lt;/p&gt;




&lt;p&gt;These were some better ways to use the Optionals in Java. If you found this helpful post consider following and leave a clap.&lt;/p&gt;

</description>
      <category>java</category>
      <category>springboot</category>
      <category>programming</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Transactions And Transaction Propagation</title>
      <dc:creator>Sohail Shah</dc:creator>
      <pubDate>Wed, 16 Aug 2023 05:14:06 +0000</pubDate>
      <link>https://forem.com/sohailshah/transactions-and-transaction-propagation-2noh</link>
      <guid>https://forem.com/sohailshah/transactions-and-transaction-propagation-2noh</guid>
      <description>&lt;p&gt;Let’s begin this post, by understanding what is a transaction&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fpz3zrhlh1gt2cewa5dz4.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fpz3zrhlh1gt2cewa5dz4.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h1&gt;
  
  
  What is a Transaction?
&lt;/h1&gt;

&lt;p&gt;To define in simple terms, a transaction is an atomic unit of work. In the context of software applications, it represents a single, coherent unit of work that consists of multiple operations.&lt;/p&gt;

&lt;p&gt;Transactions primarily belong to the context of databases. A transaction in a database represents a unit of work that consists of multiple database operations such as insert, select, update, or delete. While transactions are managed by the database itself, software applications that connect with the database play a vital role in initiating and controlling the transactions.&lt;/p&gt;

&lt;p&gt;Transactions are a fundamental aspect of relational databases and even some non-relational databases also provide transactional ability.&lt;/p&gt;

&lt;h1&gt;
  
  
  Why the need for transactions?
&lt;/h1&gt;

&lt;p&gt;The purpose of using transactions is to ensure data integrity and consistency. When multiple operations are grouped into a transaction, they are either all completed successfully or none of them are applied, which helps maintain the accuracy and reliability of the data.&lt;/p&gt;

&lt;p&gt;E-Commerce, banking and finance, reservation systems, and supply chain management are a few examples of domains where their software applications need to have consistent and accurate data to perform operations without discrepancies and guarantee reliable customer experience.&lt;/p&gt;

&lt;p&gt;Let’s take an example of buying a product from an e-commerce site. When the buy product button is clicked, the order is confirmed. To confirm the order multiple operations can take place like checking product availability, reserving the product, updating the inventory, creating the order, payment, and order confirmation.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;This is just an example, in a real case much more complicated operations take place.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The buy-product method is put in a transaction context to make sure all the operations occur or neither of them.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5tp83p205aakpml6ph2f.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5tp83p205aakpml6ph2f.png" alt="Image description"&gt;&lt;/a&gt;&lt;br&gt;
The annotation is used in spring applications to define and manage transactions for methods.&lt;/p&gt;

&lt;p&gt;When a method is marked with &lt;strong&gt;&lt;em&gt;@Transactional&lt;/em&gt;&lt;/strong&gt; annotation by default:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Changes are rollbacked if any RuntimeException is thrown by the method&lt;/li&gt;
&lt;li&gt;Changes are not rollbacked if any Checked Exception is thrown by the method&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This default behavior for rollback can be changed by passing particular &lt;strong&gt;RuntimeExceptions&lt;/strong&gt; and &lt;strong&gt;Checked Exceptions&lt;/strong&gt; for &lt;strong&gt;&lt;em&gt;rollbackFor&lt;/em&gt;&lt;/strong&gt; and &lt;strong&gt;&lt;em&gt;noRollbackFor&lt;/em&gt;&lt;/strong&gt; parameters for the &lt;strong&gt;&lt;em&gt;@Transactional&lt;/em&gt;&lt;/strong&gt; annotation&lt;/p&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&lt;br&gt;
 Java&lt;br&gt;
@Transactional(&lt;br&gt;
            rollbackFor = DuplicateUserException.class,&lt;br&gt;
            noRollbackFor = IllegalArgumentException.class&lt;br&gt;
)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h1&gt;
&lt;br&gt;
  &lt;br&gt;
  &lt;br&gt;
  Transaction Propagation&lt;br&gt;
&lt;/h1&gt;

&lt;p&gt;In spring applications, to execute a method in a transaction context, the &lt;strong&gt;&lt;em&gt;@Transactional&lt;/em&gt;&lt;/strong&gt; annotation on top of a method. When a method with a transaction calls multiple other methods, transactions are propagated from one method to another. We might want to manage the transaction propagation behavior differently to different methods depending on their functionality.&lt;/p&gt;

&lt;p&gt;From the above example, we know that single action, such as buying a product, involves carrying out several individual tasks. The buy method will include all the individual method calls to make up a single cohesive unit.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7ywh9c4clal0je9jdoza.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7ywh9c4clal0je9jdoza.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  Propagation.REQUIRED
&lt;/h4&gt;

&lt;p&gt;By default, propagation is set to required. When a method is annotated with &lt;strong&gt;&lt;em&gt;@Transactional(propagation = Propagation.REQUIRED)&lt;/em&gt;&lt;/strong&gt;, the method will always require a transaction context to execute.&lt;/p&gt;

&lt;p&gt;Method marked with &lt;strong&gt;Propagation.REQUIRED&lt;/strong&gt; when called from another method.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;If there is no transaction, a new transaction is created&lt;/li&gt;
&lt;li&gt;If a transaction is already present, the method is executed in the same transaction context&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In our example, let’s say the check product availability is marked with required propagation, so it will execute in the same transaction context as buy product method.&lt;/p&gt;

&lt;h4&gt;
  
  
  Propagation.REQUIRES_NEW
&lt;/h4&gt;

&lt;p&gt;When a method is marked with &lt;strong&gt;&lt;em&gt;@Transactional(propagation = Propagation.REQUIRES_NEW)&lt;/em&gt;&lt;/strong&gt;, a new transaction context is created every time the method is executed, even if it is called from a method with a transaction already present.&lt;/p&gt;

&lt;p&gt;There can be a requirement such that if one particular operation like sending mail is part of the buy-product method, fails for some reason you don’t want the entire transaction to fail. Because sending mail should not affect the customer buying the product.&lt;/p&gt;

&lt;h4&gt;
  
  
  Propagation.MANDATORY
&lt;/h4&gt;

&lt;p&gt;As the name suggests, when a method is marked with &lt;strong&gt;&lt;em&gt;@Transactional(propagation = Propagation.MANDATORY)&lt;/em&gt;&lt;/strong&gt;, it always requires a transaction context to execute.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Using this propagation doesn’t create a transaction of its own but makes sure that there is a transaction context when calling the method.&lt;/li&gt;
&lt;li&gt;Methods marked with mandatory, when called from a method that doesn't have any transaction will fail with an exception from the transaction manager&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  Propagation.NEVER
&lt;/h4&gt;

&lt;p&gt;When a method marked is marked with &lt;strong&gt;&lt;em&gt;@Transactional(propagation = Propagation.NEVER)&lt;/em&gt;&lt;/strong&gt;, it means never it requires a transaction context for execution.&lt;/p&gt;

&lt;p&gt;If a method is marked with &lt;strong&gt;Propagation.NEVER&lt;/strong&gt; and called from a method with a transactions context, it will with an exception. It behaves the opposite of &lt;strong&gt;Propagation.MANDATORY&lt;/strong&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  Propagation.SUPPORTS
&lt;/h4&gt;

&lt;p&gt;When a method is marked with &lt;strong&gt;&lt;em&gt;@Transactional(propagation = Propagation.NEVER)&lt;/em&gt;&lt;/strong&gt;, the method can be called from a transaction context or without a transaction context.&lt;/p&gt;

&lt;p&gt;As the name implies, it supports being executed in a transaction context but doesn’t create a new transaction on its own rather executes within the called methods transaction context. At the same time, the method can also be called from a method with no transaction context just like a normal method. &lt;strong&gt;Propagation.SUPPORTS&lt;/strong&gt; is like a middle ground for &lt;strong&gt;Propagation.MANDATORY&lt;/strong&gt; and &lt;strong&gt;Propagation.NEVER&lt;/strong&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  Propagation.NOT_SUPPORTED
&lt;/h4&gt;

&lt;p&gt;When a method is marked with &lt;strong&gt;&lt;em&gt;@Transactional(propagation = Propagation.NOT_SUPPORTED)&lt;/em&gt;&lt;/strong&gt;, the method executes without a transaction.&lt;/p&gt;

&lt;p&gt;The method can be called from a method either with a transactional or without a transaction. But even when called from a method with a transaction context, the method marked with &lt;strong&gt;Propagation.NOT_SUPPORTED&lt;/strong&gt; will always execute with any transaction context.&lt;/p&gt;

&lt;p&gt;Let’s say the buy product consists of a method that has a single select query that reads data from the database. It’s logical that this method doesn’t require any transaction for execution as it is not making any changes to the database.&lt;/p&gt;




&lt;p&gt;If you liked this post leave a reaction, we'll cover transaction isolation in another post&lt;/p&gt;

</description>
      <category>java</category>
      <category>spring</category>
      <category>springboot</category>
      <category>database</category>
    </item>
    <item>
      <title>Implement Service Discovery Pattern With Eureka And Consul</title>
      <dc:creator>Sohail Shah</dc:creator>
      <pubDate>Mon, 31 Jul 2023 12:17:38 +0000</pubDate>
      <link>https://forem.com/sohailshah/implement-service-discovery-pattern-with-eureka-and-consul-2dab</link>
      <guid>https://forem.com/sohailshah/implement-service-discovery-pattern-with-eureka-and-consul-2dab</guid>
      <description>&lt;p&gt;In the previous post, we looked at what Discovery Server in microservices is and what are the problems it solves. In the post, we’ll implement the service discovery pattern with Eureka and Consul with Spring Boot.&lt;/p&gt;

&lt;h1&gt;
  
  
  Netflix Eureka
&lt;/h1&gt;

&lt;p&gt;Netflix Eureka is one of the most popular open-source solutions to achieve service discovery. Eureka is also part of Spring Cloud tools, providing quick and easy configuration to get started.&lt;/p&gt;

&lt;p&gt;Let’s set up the discovery server. Create a spring boot application with only the following dependency. You can use the spring initializer site to create the application easily. If you don’t use the spring initializer site, make sure to add the cloud dependencies.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
 XML
&amp;lt;dependency&amp;gt;
   &amp;lt;groupId&amp;gt;org.springframework.cloud&amp;lt;/groupId&amp;gt;
   &amp;lt;artifactId&amp;gt;spring-cloud-starter-netflix-eureka-server&amp;lt;/artifactId&amp;gt;
&amp;lt;/dependency&amp;gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The next step is to add the &lt;strong&gt;&lt;em&gt;@EnableEurekaServer&lt;/em&gt;&lt;/strong&gt; annotation on top of the main class of the application. Adding this annotation is optional. It does not affect the discovery server functionality. It is just for code readability.&lt;/p&gt;

&lt;p&gt;With the dependency added and spring boot providing auto-configuration with sensible defaults, we can run the application and it’ll work fine. But you’ll see some error messages in the console that’s because by default the discovery server also acts as a discovery client and tries to register itself with other discovery servers. In this demo, we only have one discovery server. We have to configure our discovery server such that it does not act as the client itself.&lt;/p&gt;

&lt;p&gt;Configuring the discovery server can be done in two ways, either programmatically by defining beans or by defining the configuration in the &lt;strong&gt;&lt;em&gt;application.properties&lt;/em&gt;&lt;/strong&gt; or the &lt;strong&gt;&lt;em&gt;application.yml&lt;/em&gt;&lt;/strong&gt; file. It is recommended to do it in the yml file.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
 YML
spring:
  application:
    name: discovery-client

server:
  port: 8761

eureka:
  client:
    register-with-eureka: false
    fetch-registry: false


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;In the yml file, the discovery server port is set to &lt;strong&gt;8761&lt;/strong&gt; as is the default port. The Eureka client properties &lt;strong&gt;register-with-eureka&lt;/strong&gt; and &lt;strong&gt;fetch-registry&lt;/strong&gt; is set to false.&lt;/p&gt;

&lt;p&gt;Setting the register-with-eureka property to false stops the discovery server to register itself with other discovery servers and setting the &lt;strong&gt;fetch-registry&lt;/strong&gt; to false stops our discovery server to fetch registry data from other discovery servers since there is only one discovery server in this demo.&lt;/p&gt;

&lt;p&gt;Now let’s set up the discovery client(s), that can be discovered by the discovery server. The discovery client is our spring boot application providing services as a microservice. You can create a new spring boot application or use an existing application to act as a discovery client that can register itself with the discovery server.&lt;/p&gt;

&lt;p&gt;All you have to do is to add the following dependency and we are ready to run the application.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
 XML
&amp;lt;dependency&amp;gt;
   &amp;lt;groupId&amp;gt;org.springframework.cloud&amp;lt;/groupId&amp;gt;
   &amp;lt;artifactId&amp;gt;spring-cloud-starter-netflix-eureka-client&amp;lt;/artifactId&amp;gt;
&amp;lt;/dependency&amp;gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;In the application.yml file, change the name of the application to see the same name in the service registry.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
 YML
spring:
  application:
    name: discovery-client

server:
  port: 9000


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now with both applications running, visit localhost:8761 in the browser. We can see that our client application has successfully registered itself with the discovery server.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fx0ubh35u130x2w4gwl2p.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fx0ubh35u130x2w4gwl2p.png" alt="Image description"&gt;&lt;/a&gt;&lt;br&gt;
We have configured both the discovery server and the discovery client with the minimum configuration to set up the discovery service mechanism. That being said, the Netflix Eureka comes with many other features like loading balancing and there are tons of configurations available to make services secure, highly available, and resilient.&lt;/p&gt;

&lt;p&gt;Check out the &lt;a href="https://github.com/Sohailshah20/service-discovery-pattern-demo/tree/main/eureka" rel="noopener noreferrer"&gt;GitHub &lt;/a&gt;repository for the same.&lt;/p&gt;

&lt;h1&gt;
  
  
  HashiCorp Consul
&lt;/h1&gt;

&lt;p&gt;Consul is a tool developed by HashCorp, known for developing Terraform. Apart from service discovery, the consul provides a key-value store, centralised configuration, network security, and several other features. But in this post, we are only interested in the service discovery aspect of it.&lt;/p&gt;

&lt;p&gt;To get started with Consul, we can spin up a docker container or download the executable from the official site.&lt;/p&gt;

&lt;p&gt;Let’s see how to run a docker container. First, pull the consul image using the command below.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
 bash
$ docker pull hashicorp/consul


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Create and run the container on the default port 8500 with below command&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
 bash
$ docker run --name consul -d -p 8500:8500 hashicorp/consul


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The same can be done without docker by directly running the executable file downloaded.&lt;/p&gt;

&lt;p&gt;Extract the .exe file and in the directory where the file is present run the following command in the terminal&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
 bash
.\consul agent -dev -enable-script-checks -node=web -ui


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;blockquote&gt;
&lt;p&gt;Note I’m running the command on windows. For other OS check out the official documentation&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Now visit &lt;strong&gt;&lt;em&gt;localhost:8500/ui&lt;/em&gt;&lt;/strong&gt; to check out the web UI. In the services section, you can see one instance of consul discovery server running.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fffwf98exeojcpqkkudyc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fffwf98exeojcpqkkudyc.png" alt="Image description"&gt;&lt;/a&gt;&lt;br&gt;
For the microservices to register themselves to the registry, add the following dependencies in the pom.xml file&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
 XML
&amp;lt;dependency&amp;gt;
   &amp;lt;groupId&amp;gt;org.springframework.boot&amp;lt;/groupId&amp;gt;
   &amp;lt;artifactId&amp;gt;spring-boot-starter-web&amp;lt;/artifactId&amp;gt;
&amp;lt;/dependency&amp;gt;
&amp;lt;dependency&amp;gt;
   &amp;lt;groupId&amp;gt;org.springframework.cloud&amp;lt;/groupId&amp;gt;
   &amp;lt;artifactId&amp;gt;spring-cloud-starter-consul-discovery&amp;lt;/artifactId&amp;gt;
&amp;lt;/dependency&amp;gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;By adding the consul discovery dependency to the classpath of our application, spring-boot auto-configures the application to register itself with the consul service registry.&lt;/p&gt;

&lt;p&gt;Also, we need the web dependency as the service discovery mechanism is happening over the **HTTP **protocol.&lt;/p&gt;

&lt;p&gt;You can add the optional &lt;strong&gt;&lt;em&gt;@EnableDiscoveryClient&lt;/em&gt;&lt;/strong&gt; annotation on the main class of the application. In the &lt;strong&gt;&lt;em&gt;application.yml&lt;/em&gt;&lt;/strong&gt; file configure the name and port of the application.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
 YML
spring:
  application:
    name: discovery-client

server:
  port: 900


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now if we run the application and check out the consul web UI. We can see that our application has registered itself in the service registery.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fstl264fvrhv1937llji9.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fstl264fvrhv1937llji9.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Check out the &lt;a href="https://github.com/Sohailshah20/service-discovery-pattern-demo/tree/main/consul/consul-discovery-client" rel="noopener noreferrer"&gt;GitHub &lt;/a&gt;repository for the same.&lt;/p&gt;




&lt;p&gt;If you liked this post, consider leaving a reaction and follow for more.&lt;/p&gt;

</description>
      <category>java</category>
      <category>microservices</category>
    </item>
    <item>
      <title>Service Discovery in Microservices</title>
      <dc:creator>Sohail Shah</dc:creator>
      <pubDate>Wed, 26 Jul 2023 14:23:09 +0000</pubDate>
      <link>https://forem.com/sohailshah/service-discovery-in-microservices-1797</link>
      <guid>https://forem.com/sohailshah/service-discovery-in-microservices-1797</guid>
      <description>&lt;h1&gt;
  
  
  What is Service Discovery?
&lt;/h1&gt;

&lt;p&gt;In modern cloud-based applications, there are multiple services running with multiple instances of some of them. It's common that each service communicates with each other to provide services. In order to communicate with each other each service need to know the network address and port other services.&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--xzvb7kNm--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cxc46woyyw0wq1lhqltv.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--xzvb7kNm--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cxc46woyyw0wq1lhqltv.png" alt="Image description" width="800" height="454"&gt;&lt;/a&gt;&lt;br&gt;
We can hard code the network address and ports initially but we’ll run into a lot of problems quickly.&lt;/p&gt;

&lt;p&gt;What if we need to dynamically scale horizontally meaning adding more instances of a service to handle increased load? How do we load-balance the requests to each instance?&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--p7TfUiHP--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z9lamvk91qr0ogkz4r5y.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--p7TfUiHP--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z9lamvk91qr0ogkz4r5y.png" alt="Image description" width="800" height="491"&gt;&lt;/a&gt;&lt;br&gt;
In modern cloud applications, each service has its network address assigned dynamically, and the number of services running also changes frequently due to horizontal scaling.&lt;/p&gt;

&lt;p&gt;Deploying new versions of services will break the communication if paths are hardcoded, communicating with new services becomes difficult and requires a lot of manual changes. Hence the need for a service discovery mechanism.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;A service discovery acts as a registry that holds the addresses of all the instances of services&lt;/strong&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;There are two types of Service discovery patterns&lt;br&gt;
1.Client Side Discovery&lt;br&gt;
2.Server Side Discovery&lt;/p&gt;

&lt;h2&gt;
  
  
  Client Side Discovery
&lt;/h2&gt;

&lt;p&gt;In a client-side discovery mechanism, a service is responsible for determining the address of each instance available. Also, the service itself is responsible for load-balancing the requests between the instances using a suitable load-balancing algorithm.&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--wNanxVCd--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8k7w8fg1tg635esw0tgr.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--wNanxVCd--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8k7w8fg1tg635esw0tgr.png" alt="Image description" width="800" height="488"&gt;&lt;/a&gt;&lt;br&gt;
Advantages of client-side service registry:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Straight forward to implement&lt;/li&gt;
&lt;li&gt;Since addresses of instances are known beforehand, efficient load-balancing algorithms can be employed&lt;/li&gt;
&lt;li&gt;In the event that the service discovery is down, the address can be cached to continue functioning.&lt;/li&gt;
&lt;li&gt;Reduced latency as we don't have to make an extra hop if we had a centralized load balancer.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Disadvantages of client-side service registry:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The service is tightly coupled to the service registry&lt;/li&gt;
&lt;li&gt;Each service must implement client-side discovery logic for the programming language and framework used by the service.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Server Side Discovery
&lt;/h2&gt;

&lt;p&gt;In the server-side discovery mechanism, each service communicates with other services through a dedicated load balancer. The load balancer makes the request by querying the service registry and routes each request to the appropriate instance available.&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--btmgpPJl--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6s2fstpcido9u5pr9u4l.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--btmgpPJl--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6s2fstpcido9u5pr9u4l.png" alt="Image description" width="800" height="415"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Advantages of server-side discovery:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Service becomes lighter as it doesn’t have to deal with service registry lookups&lt;/li&gt;
&lt;li&gt;No need to implement service discovery logic for different languages and frameworks used by services&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Disadvantages of server-side discovery:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Set up and manage a dedicated load balancer&lt;/li&gt;
&lt;li&gt;A centralized service registry can be a single point of failure for the entire system&lt;/li&gt;
&lt;li&gt;Network latency is increased as each request has to go through the load balancer and service registry&lt;/li&gt;
&lt;/ul&gt;

&lt;h1&gt;
  
  
  Service Registration Model
&lt;/h1&gt;

&lt;p&gt;Up until now, we have assumed that the service registry already knows the addresses of the services. Let's see how services register and deregister themselves with the service registry.&lt;/p&gt;

&lt;h2&gt;
  
  
  Self-Registration
&lt;/h2&gt;

&lt;p&gt;In a self-registration model, each service has the responsibility of registering and de-registering themselves in the service registry. Once registered, the service needs to send hearts beats/ ping the service registry to keep the registration alive.&lt;/p&gt;

&lt;h2&gt;
  
  
  Third-Party Registration
&lt;/h2&gt;

&lt;p&gt;In the third-party registration model, the services are not responsible for registering themselves to the service registry. Instead, another component in the system known as the service registrar is responsible for registering the services in the service registry. The service registrar keeps track of changes by polling the deployment environment or subscribing to events. When a new service is available it registers it in the service registry and de-registers it once it gets terminated.&lt;/p&gt;

&lt;p&gt;In conclusion, service discovery is a database that has the addresses of the service instances. It must be highly available and up-to-date.&lt;/p&gt;

</description>
      <category>java</category>
      <category>microservices</category>
      <category>microservicearchitecture</category>
      <category>microservicespattern</category>
    </item>
    <item>
      <title>JPA : One-To-Many, Many-To-One And Many-To-Many Relationships</title>
      <dc:creator>Sohail Shah</dc:creator>
      <pubDate>Fri, 21 Jul 2023 10:24:06 +0000</pubDate>
      <link>https://forem.com/sohailshah/jpa-one-to-many-many-to-one-and-many-to-many-relationships-3an1</link>
      <guid>https://forem.com/sohailshah/jpa-one-to-many-many-to-one-and-many-to-many-relationships-3an1</guid>
      <description>&lt;p&gt;In the previous post, we looked at one-to-one relationship. In this post, we will look at one-to-many, many-to-one, and many-to-many relationships.&lt;/p&gt;

&lt;h1&gt;
  
  
  Many-To-One Relationship
&lt;/h1&gt;

&lt;p&gt;In a many-to-one relationship, multiple entities are associated with exactly one other entity. In terms of database tables, multiple records in a table can be associated with exactly one record in other table.&lt;/p&gt;

&lt;p&gt;To understand it better, let's create an entity called assignment. The assignment entity contains the following member variables.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
 Java
@Entity
@Table(name = "grade_table")
public class Assignment {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    private String title;
    @Temporal(value = TemporalType.DATE)
    private Date dueDate;
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The idea here is that there can be many assignments assigned to a single student. Therefore, we can establish a many to one relationship between student and assignment entities.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fi40xt601tci0zd9ft4m0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fi40xt601tci0zd9ft4m0.png" alt="Image description"&gt;&lt;/a&gt;&lt;br&gt;
To achieve this, we are going to use the &lt;strong&gt;@ManyToOne&lt;/strong&gt; annotation. Now the question is in which entity do we put this annotation? In the student entity or in the assignment entity?&lt;/p&gt;

&lt;p&gt;While modeling these kinds of relationships we also need to understand how table records are going to be affected, only then we can decide in which entity to put the annotation.&lt;/p&gt;

&lt;p&gt;Let's assume we simply put in the student entity as we did in one to one relationship. Then it is expected that there is a foreign key column in the student table with the primary keys of assignment entities. since a student can have more than one assignment storing multiple keys in a single column is not possible.&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F998fhdjn90vnpp8ekzb1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F998fhdjn90vnpp8ekzb1.png" alt="Image description"&gt;&lt;/a&gt;&lt;br&gt;
It should be noticed that multiple assignments are going to be assigned to a single student. So instead we can store student ids in the foreign key column of the assignment table. Let's do that now&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
 Java
@Entity
@Table(name = "grade_table")
public class Assignment {
    .
    .
    .
    @ManyToOne
    private Student assignedTo;
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Create a couple of new assignment objects and persist them in the database with the new relationship. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
 Java
Assignment assl = new Assignment();
assl.setTitle("JAVA");
assl.setDueDate(new Date());
assl.setAssignedTo(studentl) ;
Assignment ass2 = new Assignment();
ass2.setTitte("DSA");
ass2.setDueDate(new Date()) ;
ass2.setAssignedTo(studentl) ;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;In the database, we can see there is no change to the student table. The new assignment table has two assignments with the same student ids.&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2ba2wqnstog5h9yl36wu.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2ba2wqnstog5h9yl36wu.png" alt="Image description"&gt;&lt;/a&gt;&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fr66g6lfn9dnxthfg5era.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fr66g6lfn9dnxthfg5era.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h1&gt;
  
  
  One-To-Many Relationship
&lt;/h1&gt;

&lt;p&gt;If fetch student details we won't be able to get the assignments assigned to the students. That's because the student entity has no access to the assignment entity. As we have seen in the one-to-one relationship we can solve this by simply mirroring the relationship in the student entity. When mirroring the relationship it is important to define a primary entity and the other entity automatically becomes the mirrored entity. Which entity becomes the primary is up to the database design and the data itself. We discussed it in the previous post. Check it out to understand it in more detail and other implications of it.&lt;/p&gt;

&lt;p&gt;To mirror the many-to-one relationship in the student entity, we need a list of assignments because there can be many assignments for a student.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
 Java
@Entity
@Table(name = "Student_Table")
public class Student {
    .
    .
    .
    @OneToMany(mappedBy = "assignedTo")
    private List&amp;lt;Assignment&amp;gt; assignmentList;
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;One-to-many and many-to-one mirror each other. Sometimes we can get confused about which annotation to use in which entity. well here’s a trick, In the above example Student entity has many assignment entities. Read it as &lt;strong&gt;one&lt;/strong&gt; student has &lt;strong&gt;many&lt;/strong&gt; assignments. Thus &lt;strong&gt;@OneToMany&lt;/strong&gt; annotation. In the same way, the assignment entity read it as &lt;strong&gt;many&lt;/strong&gt; assignments but &lt;strong&gt;one&lt;/strong&gt; student thus &lt;strong&gt;@ManyToOne&lt;/strong&gt; annotation.&lt;/p&gt;

&lt;p&gt;Let's fetch the student details again and see the result.&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fo9fkju7iay1to8fjgvjq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fo9fkju7iay1to8fjgvjq.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Since student and assignment entities mirror each other's relationship, make sure to format the &lt;strong&gt;toSting()&lt;/strong&gt; method in both entities properly so that they don't access each other's data resulting in an infinite loop.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The two assignments are present in the student details. Now we can easily access the assignment data from the student data and vice versa.&lt;/p&gt;

&lt;h2&gt;
  
  
  Fetch Type
&lt;/h2&gt;

&lt;p&gt;In the previous post, we saw that the default fetch type is eager. But that's not the case with many-to-one and one-to-many relationships. The default fetch type is &lt;strong&gt;lazy&lt;/strong&gt;. It makes sense because we don't want to fetch different multiple entities along with the student entity. The assignment data is fetched only when it is accessed.&lt;/p&gt;

&lt;p&gt;Do check the hibernate-generated queries to understand more in detail.&lt;/p&gt;

&lt;h1&gt;
  
  
  Many-To-Many Relationship
&lt;/h1&gt;

&lt;p&gt;To understand the many-to-many relationship let's create an entity called club. The club entity contains the following member variables&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
 Java
@Entity
@Table(name = "Student_club")
public class Club {
    @Id
    @GeneratedValue
    private int id;
    private int name;
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;In a many-to-many relationship, multiple records in one table can be associated with multiple records in another table. In our example, a student can be part of many clubs, and a club can have many students. To represent this relationship in a database, we typically use a junction table or an associative table.&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhcj2sd26vqdmaosvijdm.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhcj2sd26vqdmaosvijdm.png" alt="Image 1"&gt;&lt;/a&gt; &lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F112ouw805q7125szil60.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F112ouw805q7125szil60.png" alt="Image 2"&gt;&lt;/a&gt;&lt;br&gt;
In the case of one-to-many and many-to-one relationships, we noticed that a foreign key in a table can reference only one primary key. So we referenced the primary keys of the student to the foreign key column of the assignment table. But in the case of many-to-many relationship, it is not possible to directly use a single foreign key to establish the association between the two entities. This is because both entities are associated with multiple instances of each other.&lt;/p&gt;

&lt;p&gt;This problem is solved using a junction table approach. A junction table is an entirely new table that acts as a bridge between the two entities and establishes the many-to-many relationship. In a junction table, there exits foreign key columns that contain the primary keys of both entities.&lt;/p&gt;

&lt;p&gt;Now let's add the &lt;strong&gt;@ManyToMany&lt;/strong&gt; annotation to the member variables of the entities we want.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
 Java
@Entity
@Table(name = "Student_club")
public class Club {
    @Id
    @GeneratedValue
    private int id;
    private int name;
    @ManyToMany
    private List&amp;lt;Student&amp;gt; studentList;
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
 Java
@Entity
@Table(name = "Student_Table")
public class Student {
        .
        .
    @ManyToMany  
    private List&amp;lt;Club&amp;gt; clubs;
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;If you noticed, the members are of type list indicating the kind of relationship we are establishing here. We might have members annotated the variables are annotated with &lt;strong&gt;@ManyToMany&lt;/strong&gt; but it doesn’t precisely establish the relation as we want. &lt;/p&gt;

&lt;p&gt;Let's create a couple of club and student objects and persist them in the database. By doing so we can observe what exactly happens to the database tables.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
 Java
//Student 1 object
Student student1 = new Student();
student1.setName("Sohail Shah");
student1.setAge(18);
student1.setAdmission_no("1234");
student1.setDob(new Date());
student1.setStudentType(StudentType.SCHOLARSHIP);
//Student 2 object
Student student2 = new Student();
student2.setName("Ali");
student2.setAge(20);
student2.setAdmission_no("1235");
student2.setDob(new Date());
student2.setStudentType(StudentType.NON_SCHOLARSHIP);
//club 1 object
Club club1 = new Club();
club1.setName("Java Club");
club1.addStudent(student1);
club1.addStudent(student2);
student1.addClub(club1);
student2.addClub(club1);
//club 2 object
Club club2 = new Club();
club2.setName("Spring Club");
club2.addStudent(student2);
student2.addClub(club2);
student1.addClub(club1);
student1.addClub(club2);
student2.addClub(club1);
student2.addClub(club2);
//persisting the objects                
entityManager.persist(student1);
entityManager.persist(student2);
entityManager.persist(club1);
entityManager.persist(club2);


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;After running the application, in the database, we'll have two different tables with the same data or foreign keys that are just mirrored.&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fx7zsf16q5st6up5atd03.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fx7zsf16q5st6up5atd03.png" alt="Image description"&gt;&lt;/a&gt;&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fgt0lvncj38xtf4l3rd1y.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fgt0lvncj38xtf4l3rd1y.png" alt="Image description"&gt;&lt;/a&gt;&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fl8ae8dwtwauz0n6o75o0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fl8ae8dwtwauz0n6o75o0.png" alt="Image description"&gt;&lt;/a&gt;&lt;br&gt;
The JPA doesn't know both these tables contain the same data and it is tracking them twice.&lt;/p&gt;

&lt;p&gt;This is easily solved by using the mappedBy parameter in the many-to-many annotation. We have used this in other relationships too. You can put the mappedBy in any of the entities.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
 Java
@ManyToMany(mappedBy = "clubs")
private List&amp;lt;Student&amp;gt; studentList = new ArrayList&amp;lt;&amp;gt;()


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;If we run the application again, there should be only one table containing the primary keys of both entities.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Make sure you properly use &lt;code&gt;&amp;lt;property name="hibernate.hbm2ddl.auto" value="create"/&amp;gt;&lt;/code&gt; in order to see the correct data. If getting errors just drop tables and run the application again.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fug26lcppsbdgn40xxa3h.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fug26lcppsbdgn40xxa3h.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Fetch
&lt;/h2&gt;

&lt;p&gt;The default fetch type for many-to-many relationship is lazy same as one-to-many and many-to-one. You can of course change this default behaviour by using the &lt;strong&gt;FETCH.EAGER&lt;/strong&gt; and &lt;strong&gt;FETCH.LAZY&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Deciding the fetch type depends on your database schema and needs. A lazy fetch type is usually recommended for many-to-many relationships.&lt;/p&gt;

</description>
      <category>java</category>
      <category>jpa</category>
      <category>hibernate</category>
      <category>spring</category>
    </item>
    <item>
      <title>Different Ways To Use Comparator Interface in Java</title>
      <dc:creator>Sohail Shah</dc:creator>
      <pubDate>Sat, 15 Jul 2023 13:45:32 +0000</pubDate>
      <link>https://forem.com/sohailshah/different-ways-to-use-comparator-interface-in-java-4mgj</link>
      <guid>https://forem.com/sohailshah/different-ways-to-use-comparator-interface-in-java-4mgj</guid>
      <description>&lt;p&gt;In this post, we will explore various ways to use the Comparator interface in Java to compare objects and sort collections&lt;/p&gt;

&lt;p&gt;Let's assume we have a list of Student objects, with a Student class that has some member variables. We'll use this as an example through the post.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Student&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;firstName&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;lastName&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;Date&lt;/span&gt; &lt;span class="n"&gt;age&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Student&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;list&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;ArrayList&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;();&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  1. Create a Class Implementing Comparator
&lt;/h2&gt;

&lt;p&gt;One way to use the Comparator interface is by creating a separate class that implements the Comparator interface. This class will provide the logic for comparing objects based on specific criteria. You can then instantiate this class and use it to sort collections of objects. This approach allows for a flexible and reusable way of defining custom sorting logic.&lt;/p&gt;

&lt;p&gt;Now let's create our custom class that implements the Comparator Interface&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;StudentComparator&lt;/span&gt; &lt;span class="kd"&gt;implements&lt;/span&gt; &lt;span class="nc"&gt;Comparator&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Student&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;{&lt;/span&gt;
    &lt;span class="nd"&gt;@Override&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="nf"&gt;compare&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Student&lt;/span&gt; &lt;span class="n"&gt;o1&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Student&lt;/span&gt; &lt;span class="n"&gt;o2&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;o1&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getId&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;o2&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getId&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This class compares the students based on their id's. Now passing an instance of this class in the sort method of the Collections util class sorts the list in ascending order of id's&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;StudentComparator&lt;/span&gt; &lt;span class="n"&gt;studentComparator&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;StudentComparator&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
&lt;span class="nc"&gt;Collections&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;sort&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;list&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt;&lt;span class="n"&gt;studentComparator&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is one way to use the Comparator interface. You can create multiple classes implementing the comparator interface for different custom sorting logic.&lt;/p&gt;

&lt;h2&gt;
  
  
  2. Using Lambda Expressions
&lt;/h2&gt;

&lt;p&gt;Another way to utilize the Comparator interface is by using lambda expressions. Lambda expressions provide a concise way to define the comparison logic inline, without the need to create a separate class. This approach is often preferred for simple comparisons and can lead to more readable code.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;Comparator&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Student&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;compareWithId&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;s1&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;s2&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;s1&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getId&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;s2&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getId&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
&lt;span class="n"&gt;list&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;sort&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;compareWithId&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  3. Using Method Reference
&lt;/h2&gt;

&lt;p&gt;Method reference is another approach to using the Comparator interface. It allows you to refer to an existing method and use it as the comparison logic. This approach can be useful when you have an existing method that already provides the desired comparison behavior. Method references reduce code duplication and enhance code readability.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="n"&gt;list&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;sort&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Comparator&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;comparing&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nl"&gt;Student:&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;&lt;span class="n"&gt;getFirstName&lt;/span&gt;&lt;span class="o"&gt;));&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is so much simple than the previous ones.&lt;/p&gt;

&lt;h2&gt;
  
  
  4. Creating a Utility Class
&lt;/h2&gt;

&lt;p&gt;If you find yourself using the same comparison logic across multiple projects or classes, it may be beneficial to create a utility class. This utility class can contain static methods that implement the comparison logic you need. By encapsulating the comparison logic in a utility class, you can easily reuse it and keep your code clean and organized.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;StudentUtil&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="nc"&gt;Comparator&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Student&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;compareById&lt;/span&gt;&lt;span class="o"&gt;(){&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nc"&gt;Comparator&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;comparing&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nl"&gt;Student:&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;&lt;span class="n"&gt;getId&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="nc"&gt;Comparator&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Student&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;compareByFirstName&lt;/span&gt;&lt;span class="o"&gt;(){&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nc"&gt;Comparator&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;comparing&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nl"&gt;Student:&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;&lt;span class="n"&gt;getFirstName&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="nc"&gt;Comparator&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Student&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;compareByLastName&lt;/span&gt;&lt;span class="o"&gt;(){&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nc"&gt;Comparator&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;comparing&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nl"&gt;Student:&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;&lt;span class="n"&gt;getLastName&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="nc"&gt;Comparator&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Student&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;compareByAge&lt;/span&gt;&lt;span class="o"&gt;(){&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nc"&gt;Comparator&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;comparing&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nl"&gt;Student:&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;&lt;span class="n"&gt;getAge&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now you can use the static methods of the utility class in multiple classes in your project.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="n"&gt;list&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;sort&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;StudentUtil&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;compareByAge&lt;/span&gt;&lt;span class="o"&gt;());&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;By exploring these different ways of using the Comparator interface, you can gain a deeper understanding of how to compare objects and sort collections based on different criteria. Each approach has its own benefits and can be selected based on the complexity of the comparison logic and the specific requirements of your project.&lt;/p&gt;

&lt;p&gt;I hope this blog post helps you in understanding the different ways to use the Comparator interface. Happy coding!&lt;/p&gt;




&lt;p&gt;Follow me on : &lt;a href="//twitter.com/sohail__shah_"&gt;Twitter&lt;/a&gt;, &lt;a href="//linkedin.com/in/sohailshah20"&gt;LinkedIn&lt;/a&gt;, &lt;a href="//github.com/sohailshah20"&gt;GitHub&lt;/a&gt;, &lt;a href="//linktr.ee/sohailshah20"&gt;Linktree&lt;/a&gt;&lt;/p&gt;

</description>
      <category>java</category>
      <category>interview</category>
      <category>programming</category>
    </item>
    <item>
      <title>JPA: One-To-One Relationship, Fetch type, Relationship Direction, And Query Optimization</title>
      <dc:creator>Sohail Shah</dc:creator>
      <pubDate>Tue, 11 Jul 2023 15:26:11 +0000</pubDate>
      <link>https://forem.com/sohailshah/jpa-one-to-one-relationship-fetch-type-relationship-direction-and-query-optimization-20je</link>
      <guid>https://forem.com/sohailshah/jpa-one-to-one-relationship-fetch-type-relationship-direction-and-query-optimization-20je</guid>
      <description>&lt;p&gt;In the previous posts, we had only a single entity called the student. Let's create another entity named the library card. The library card entity will have its own table in the database with its own primary id column.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Entity&lt;/span&gt;
&lt;span class="nd"&gt;@Table&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"library_card"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;LibraryCard&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="nd"&gt;@Id&lt;/span&gt;
    &lt;span class="nd"&gt;@GeneratedValue&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="nd"&gt;@Temporal&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;TemporalType&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;DATE&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;Date&lt;/span&gt; &lt;span class="n"&gt;issuedDate&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;boolean&lt;/span&gt; &lt;span class="n"&gt;isActive&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Just like the student entity we have annotated the library card with &lt;strong&gt;@Entity&lt;/strong&gt; annotation and its member variables with proper annotations.&lt;/p&gt;

&lt;p&gt;We can create and persist library card entities in the database just like we persisted the student entities. What we want to do here is for each student to have exactly one library card.&lt;/p&gt;

&lt;p&gt;To do it a simple way we might add a library card member variable in the student entity and store the primary key values of the corresponding library card in It. Using these primary key values of library cards we can reference the library cards table itself.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Entity&lt;/span&gt;
&lt;span class="nd"&gt;@Table&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"student_table"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Student&lt;/span&gt;&lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="o"&gt;.&lt;/span&gt;
    &lt;span class="o"&gt;.&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;library_card&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;.&lt;/span&gt;
    &lt;span class="o"&gt;.&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That might look simple and easy, but doing things that way will only create tons of problems in the future causing database inconsistencies.&lt;/p&gt;

&lt;p&gt;Apart from that, we really didn't create any relationship between the two tables in the database or in the Java side of things. The library card column in the student table only contains a value that is supposed to be a primary key for the library card table but doesn't guarantee it.&lt;/p&gt;

&lt;p&gt;The solution for this problem is relationships provided by JPA. The different relationships we can define are one-to-one, one-to-many, many-to-one and many-to-many.&lt;/p&gt;

&lt;p&gt;Using a proper relationship for tables requires us to understand our data itself. In our example, each student can have only one library card. So the proper relationship to use here is a one-to-one, relationship.&lt;/p&gt;

&lt;h2&gt;
  
  
  One to One relationship
&lt;/h2&gt;

&lt;p&gt;In a one-to-one relationship, one entity is associated with exactly one other entity. In terms of database tables, each record in a table is associated with exactly one record in another table. In our example, one student can have only one library card and vice versa.&lt;/p&gt;

&lt;p&gt;In our student entity, instead of a member variable library card which is of primitive type int let's replace it with a variable card of type LibraryCard which is a entity itself.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Entity&lt;/span&gt;
&lt;span class="nd"&gt;@Table&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"student_table"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Student&lt;/span&gt;&lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="o"&gt;.&lt;/span&gt;
    &lt;span class="o"&gt;.&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;LibraryCard&lt;/span&gt; &lt;span class="n"&gt;card&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;.&lt;/span&gt;
    &lt;span class="o"&gt;.&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If we run our application we’ll get an error, that’s because hibernate doesn’t know how to persist the non-primitive type card member.&lt;/p&gt;

&lt;p&gt;The annotation we are looking for is &lt;strong&gt;@OneToOne&lt;/strong&gt;. By sticking this annotation on top of our card variable we telling JPA about the relationship we want to have between the library card entity and the the student entity.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@OneToOne&lt;/span&gt;
&lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;LibraryCard&lt;/span&gt; &lt;span class="n"&gt;card&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now let's create a couple of library cards and persist them in the database just like we persisted student entities.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Main&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt; &lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="nc"&gt;EntityManagerFactory&lt;/span&gt; &lt;span class="n"&gt;entityManagerFactory&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Persistence&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;createEntityManagerFactory&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"myPersistenceUnit"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="nc"&gt;EntityManager&lt;/span&gt; &lt;span class="n"&gt;entityManager&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;entityManagerFactory&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;createEntityManager&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;

        &lt;span class="nc"&gt;Student&lt;/span&gt; &lt;span class="n"&gt;student1&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Student&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
        &lt;span class="n"&gt;student1&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setName&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Sohail Shah"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;student1&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setAge&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;18&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;student1&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setAdmission_no&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"1234"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;student1&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setDob&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Date&lt;/span&gt;&lt;span class="o"&gt;());&lt;/span&gt;
        &lt;span class="n"&gt;student1&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setStudentType&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;StudentType&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;SCHOLARSHIP&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;

        &lt;span class="nc"&gt;Student&lt;/span&gt; &lt;span class="n"&gt;student2&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Student&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
        &lt;span class="n"&gt;student2&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setName&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Ali"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;student2&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setAge&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;20&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;student2&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setAdmission_no&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"1235"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;student2&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setDob&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Date&lt;/span&gt;&lt;span class="o"&gt;());&lt;/span&gt;
        &lt;span class="n"&gt;student2&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setStudentType&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;StudentType&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;NON_SCHOLARSHIP&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;

        &lt;span class="nc"&gt;LibraryCard&lt;/span&gt; &lt;span class="n"&gt;card1&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;LibraryCard&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
        &lt;span class="n"&gt;card1&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setActive&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;card1&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setIssuedDate&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Date&lt;/span&gt;&lt;span class="o"&gt;());&lt;/span&gt;

        &lt;span class="nc"&gt;LibraryCard&lt;/span&gt; &lt;span class="n"&gt;card2&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;LibraryCard&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
        &lt;span class="n"&gt;card2&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setActive&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="kc"&gt;false&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;card2&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setIssuedDate&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Date&lt;/span&gt;&lt;span class="o"&gt;());&lt;/span&gt;

        &lt;span class="nc"&gt;EntityTransaction&lt;/span&gt; &lt;span class="n"&gt;transaction&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;entityManager&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getTransaction&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
        &lt;span class="n"&gt;transaction&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;begin&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
        &lt;span class="n"&gt;entityManager&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;persist&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;student1&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;entityManager&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;persist&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;student2&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;entityManager&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;persist&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;card1&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;entityManager&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;persist&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;card2&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;transaction&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;commit&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
        &lt;span class="n"&gt;entityManager&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;close&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
        &lt;span class="n"&gt;entityManagerFactory&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;close&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--7sjjzS1L--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gzmhlrrnz9j5l5og74w2.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--7sjjzS1L--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gzmhlrrnz9j5l5og74w2.png" alt="Image description" width="679" height="130"&gt;&lt;/a&gt;&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--6PG3pcHs--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g0sxsonphfmh4bvbgmdy.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--6PG3pcHs--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g0sxsonphfmh4bvbgmdy.png" alt="Image description" width="311" height="134"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This is how the database currently looks. card_id column is set to null because we have set the relationship between the tables but haven't set the values for it. Let's do that now.&lt;/p&gt;

&lt;p&gt;Add these lines before persisting the entities.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="n"&gt;student1&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setCard&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;card1&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
&lt;span class="n"&gt;student2&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setCard&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;card2&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If we look at our database now we can see that the primary keys of the library cards are present in the card id column of the student table&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--1Yu3TXL1--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ux1fjjudrub2rb12773d.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--1Yu3TXL1--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ux1fjjudrub2rb12773d.png" alt="Image description" width="705" height="137"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This might look the same as we tried to do without the &lt;strong&gt;@OneToOne&lt;/strong&gt; annotation just by simply storing the primary key. But here we have actually defined an actual relationship between the two tables.&lt;/p&gt;

&lt;p&gt;The card_id column contains the key called the foreign key. The Foreign key is important in databases because it helps create relationships between tables. This foreign key column contains the primary key of a different table. There are different types of keys available like the composite key, alternate key, super key, and several other keys. These keys are used for different purposes in a database.&lt;/p&gt;

&lt;p&gt;Now that we have a relationship between our entities, it becomes easier to work with them. This relationship brings referential integrity to our database. It ensures correct values are inserted and manages the data consistency for us.&lt;/p&gt;

&lt;h2&gt;
  
  
  Fetching
&lt;/h2&gt;

&lt;p&gt;Let's fetch a student from the database and see what it looks like now that it has a relationship with the library card table.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;EntityManagerFactory&lt;/span&gt; &lt;span class="n"&gt;entityManagerFactory&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Persistence&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;createEntityManagerFactory&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"myPersistenceUnit"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
&lt;span class="nc"&gt;EntityManager&lt;/span&gt; &lt;span class="n"&gt;entityManager&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;entityManagerFactory&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;createEntityManager&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
&lt;span class="nc"&gt;Student&lt;/span&gt; &lt;span class="n"&gt;student1&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;entityManager&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;find&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Student&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;class&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
&lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;student1&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;Add proper toString() method to entities for them to print correctly&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--tisowXsR--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jminso5njcwd0gem8xzi.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--tisowXsR--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jminso5njcwd0gem8xzi.png" alt="Image description" width="800" height="30"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This is the result of the fetch. Notice that we only fetched the student details but along with it it also fetched the library card details. Since the one-to-one relationship is defined between the two entities, fetching hibernate generates a join query also to fetch the library card details.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--1g3DTJPU--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2i6yast55kok8xa55ljp.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--1g3DTJPU--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2i6yast55kok8xa55ljp.png" alt="Image description" width="497" height="674"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This behaviour can be suitable in some situations and not in others. For example, let's say our student entity has multiple other relationships with different entities. So when we fetch student details, all the other entities which are in a relationship are also fetched. But we might not want the data of all entities in relationship with the student entity.&lt;/p&gt;

&lt;p&gt;JPA provides a way to change this behaviour of fetching. We can change this behaviour by configuring the one-to-one annotation. There are two fetch types. The Eager fetch and the lazy fetch. &lt;/p&gt;

&lt;h3&gt;
  
  
  Eager Fetch
&lt;/h3&gt;

&lt;p&gt;By default, one-to-one annotation is set to eager fetch type. When the fetch type is set to eager the relationship data is fetched along with owner entity data, as we have seen above.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@OneToOne&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;fetch&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;FetchType&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;EAGER&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
&lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;LibraryCard&lt;/span&gt; &lt;span class="n"&gt;card&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Lazy Fetch
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@OneToOne&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;fetch&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;FetchType&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;LAZY&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
&lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;LibraryCard&lt;/span&gt; &lt;span class="n"&gt;card&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When the fetch type is set to lazy, the relationship data is not fetched instantaneously. It is only fetched when it is needed.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--0rlCgUGq--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/03qtiz66mh856lhhl1ru.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--0rlCgUGq--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/03qtiz66mh856lhhl1ru.png" alt="Image description" width="484" height="776"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If we run the application with fetch type lazy, In the generated query you can see there is no join clause. The library card data is fetched as a separate query when required. &lt;/p&gt;

&lt;h2&gt;
  
  
  Relationship Direction
&lt;/h2&gt;

&lt;p&gt;The direction of a relationship can be unidirectional or bidirectional.&lt;/p&gt;

&lt;p&gt;In a unidirectional relationship, one entity acts as the owner of another entity. In our case, logically speaking, a student must possess a library card and not the other way around. Therefore, the student entity owns the library card entity. The student entity can access the library card entity's data. However, the library card entity cannot access the student entity's data without explicitly writing queries for it.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--b_P_8ZeP--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8owjt5u1f1jd8cz0gg1k.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--b_P_8ZeP--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8owjt5u1f1jd8cz0gg1k.png" alt="Image description" width="799" height="260"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In a bidirectional relationship, both entities have access to each other's data without writing queries explicitly.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--_ymWoXQZ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fodfblxu5ofjrflvtv5h.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--_ymWoXQZ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fodfblxu5ofjrflvtv5h.png" alt="Image description" width="791" height="241"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;To make a bidirectional relationship between student and library card entities, we have to add the Student as a member variable in the library card entity with one-to-one mapping.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Entity&lt;/span&gt;
&lt;span class="nd"&gt;@Table&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"library_card"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;LibraryCard&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="nd"&gt;@Id&lt;/span&gt;
    &lt;span class="nd"&gt;@GeneratedValue&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="nd"&gt;@Temporal&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;TemporalType&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;DATE&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;Date&lt;/span&gt; &lt;span class="n"&gt;issuedDate&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;boolean&lt;/span&gt; &lt;span class="n"&gt;isActive&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

    &lt;span class="nd"&gt;@OneToOne&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;Student&lt;/span&gt; &lt;span class="n"&gt;owner&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Before persisting the student and library card entities, add the following lines and run the application. Our database should look like this. Both the student table and card table store information about each other.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="n"&gt;card1&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setOwner&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;student1&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
&lt;span class="n"&gt;card2&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setOwner&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;student2&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--qnZOCo2R--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tefvloglk1wnaj87p9m9.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--qnZOCo2R--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tefvloglk1wnaj87p9m9.png" alt="Image description" width="694" height="149"&gt;&lt;/a&gt;&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--EayD5PNQ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7pe2cf9xboppcs4xj5cc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--EayD5PNQ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7pe2cf9xboppcs4xj5cc.png" alt="Image description" width="378" height="141"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;With this, we have access to student entity data with library card.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;LibraryCard&lt;/span&gt; &lt;span class="n"&gt;libraryCard&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;entityManager&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;find&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;LibraryCard&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;class&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
&lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;libraryCard&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getOwner&lt;/span&gt;&lt;span class="o"&gt;());&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--rQ_X79Xv--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2r0prgxt9n1letzsqshi.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--rQ_X79Xv--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2r0prgxt9n1letzsqshi.png" alt="Image description" width="800" height="40"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We are able to get the student details. But let's look at the generated query.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--kwJB79YG--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r1mifkerjh79enb33i8s.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--kwJB79YG--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r1mifkerjh79enb33i8s.png" alt="Image description" width="487" height="781"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Library card details are being accessed multiple times as the library card is present in the student entity as well, even though we already have the card details. Hibernate doesn't recognize that the same library card is being queried again, even though they are in a bidirectional relationship. This is inefficient and can lead to issues.&lt;/p&gt;

&lt;p&gt;What we want is to inform Hibernate that the student entity is the primary entity and the library card entity is its mirror. So when we query for a student, we also want to retrieve the library card details. However, when we query the student details from the library card entity, which also contains the same library card, we don't want to perform an additional query. This can be achieved by using the &lt;strong&gt;"mappedBy"&lt;/strong&gt; parameter in the OneToOne annotation.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@OneToOne&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;mappedBy&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"card"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
&lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;Student&lt;/span&gt; &lt;span class="n"&gt;owner&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now when we run the application again, the library card is queried only once.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--3ZBuUfHF--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kljafpgzhdea3ht7adgn.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--3ZBuUfHF--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kljafpgzhdea3ht7adgn.png" alt="Image description" width="496" height="678"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In this post, we have not only covered the one-to-one relationship, but also the fetch types that determine when to fetch data, the direction of relationships, and optimizing queries.&lt;/p&gt;

&lt;p&gt;If you liked this post, please leave a reaction.&lt;/p&gt;




&lt;p&gt;Follow me on : &lt;a href="//twitter.com/sohail__shah_"&gt;Twitter&lt;/a&gt;, &lt;a href="//linkedin.com/in/sohailshah20"&gt;LinkedIn&lt;/a&gt;, &lt;a href="//github.com/sohailshah20"&gt;GitHub&lt;/a&gt;, &lt;a href="//linktr.ee/sohailshah20"&gt;Linktree&lt;/a&gt;&lt;/p&gt;

</description>
      <category>java</category>
      <category>springboot</category>
      <category>jpa</category>
      <category>hibernate</category>
    </item>
    <item>
      <title>Dive into the Spring Security Architecture</title>
      <dc:creator>Sohail Shah</dc:creator>
      <pubDate>Sun, 02 Jul 2023 13:06:16 +0000</pubDate>
      <link>https://forem.com/sohailshah/dive-into-the-spring-security-architecture-1dhf</link>
      <guid>https://forem.com/sohailshah/dive-into-the-spring-security-architecture-1dhf</guid>
      <description>&lt;p&gt;In this post, we'll be looking at the components that form spring security and understand how the spring security architecture works. By getting to know the components of spring security and their working, it becomes easy to configure and implement our own security mechanisms.&lt;/p&gt;

&lt;h2&gt;
  
  
  Components of Spring Security
&lt;/h2&gt;

&lt;p&gt;The following are the basic components that form the spring security architecture. &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Filters&lt;/li&gt;
&lt;li&gt;Authentication Manager&lt;/li&gt;
&lt;li&gt;Authentication Provider&lt;/li&gt;
&lt;li&gt;User Details Service&lt;/li&gt;
&lt;li&gt;Password Encoder&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--vcUQ0ImF--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k5c6isf4ci6ippivd60v.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--vcUQ0ImF--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k5c6isf4ci6ippivd60v.png" alt="Image description" width="800" height="838"&gt;&lt;/a&gt;&lt;br&gt;
Let's talk about each one of them in detail&lt;/p&gt;
&lt;h3&gt;
  
  
  Filters
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--c9CYzr7_--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9vnsy8ttlbz6gybyau57.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--c9CYzr7_--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9vnsy8ttlbz6gybyau57.png" alt="Image description" width="800" height="179"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In spring applications, every request needs to pass through a chain of filters before the request ends up in the controller class. These filters are responsible for the authentication and authorization of users and their requests to access resources.&lt;br&gt;
The filters check the validity of each request based on internal rules defined. You can create your custom filters with your own rules.&lt;/p&gt;

&lt;p&gt;Let's say the request is in the authentication filter. The authentication filter is responsible for extracting user authentication details and tokens. These user details are packaged as authentication objects and passed to &lt;strong&gt;Authentication Manager&lt;/strong&gt;.&lt;br&gt;
The auth object is created using an implementation &lt;strong&gt;Authentication&lt;/strong&gt; interface such as UsernamePasswordAuthenticationToken.&lt;/p&gt;
&lt;h3&gt;
  
  
  Authentication Manager
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--ocAbSQHS--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1tmhrko5wjoy9h3pb65y.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--ocAbSQHS--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1tmhrko5wjoy9h3pb65y.png" alt="Image description" width="800" height="810"&gt;&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;interface&lt;/span&gt; &lt;span class="nc"&gt;AuthenticationManager&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="nc"&gt;Authentication&lt;/span&gt; &lt;span class="nf"&gt;authenticate&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Authentication&lt;/span&gt; &lt;span class="n"&gt;authentication&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="kd"&gt;throws&lt;/span&gt; &lt;span class="nc"&gt;AuthenticationException&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;strong&gt;Authentication Manager&lt;/strong&gt; receives an authentication object from the authentication filter. &lt;strong&gt;Authentication Manager&lt;/strong&gt; is an object whose responsibility is to find a way to authenticate users. That is achieved by using &lt;strong&gt;Authentication Provider&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;In a typical spring security configuration, there is only one &lt;strong&gt;Authentication Manager&lt;/strong&gt; which delegates the authentication request to the correct &lt;strong&gt;Authentication Provider&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;Authentication Manager&lt;/strong&gt; interface has only one method called authenticate that takes in an authentication object passed down from the authentication filter. Upon successful authentication of the user, the &lt;strong&gt;Authentication Manager&lt;/strong&gt; returns an authenticated &lt;strong&gt;Authentication&lt;/strong&gt; object.&lt;/p&gt;

&lt;h3&gt;
  
  
  Authentication Provider
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--ImCqM3w8--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h1utb3ysq2x5tapjedat.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--ImCqM3w8--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h1utb3ysq2x5tapjedat.png" alt="Image description" width="800" height="575"&gt;&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;interface&lt;/span&gt; &lt;span class="nc"&gt;AuthenticationProvider&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="nc"&gt;Authentication&lt;/span&gt; &lt;span class="nf"&gt;authenticate&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Authentication&lt;/span&gt; &lt;span class="n"&gt;authentication&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="kd"&gt;throws&lt;/span&gt; &lt;span class="nc"&gt;AuthenticationException&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

    &lt;span class="kt"&gt;boolean&lt;/span&gt; &lt;span class="nf"&gt;supports&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Class&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;?&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;authentication&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There can be multiple Authentication Providers in a spring security context. Every &lt;strong&gt;Authentication Provider&lt;/strong&gt; is responsible for handling different authentication mechanisms. For example, a spring application can have both username and password authentication as well as HttpBasic authentication. For both of these authentication mechanisms, there will be an &lt;strong&gt;Authentication Provider&lt;/strong&gt; implementation.&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;Authentication Provider&lt;/strong&gt; interface has a authenticate method like the &lt;strong&gt;Authentication Manager&lt;/strong&gt; and a supports method.&lt;br&gt;
The supports method checks if the current provider supports the authentication for the given type of credentials, if not the credentials are passed to the next provider/filter.&lt;/p&gt;

&lt;p&gt;The authenticate method actually validates the credentials or tokens of the user. This method gets the user details using the UserDetailsService interface which is responsible for retrieving user details from a user store-like database. Upon successful authentication, the method returns an authenticated &lt;strong&gt;Authentication&lt;/strong&gt; object back to the &lt;strong&gt;Authentication Manager&lt;/strong&gt;. At last, this authenticated object is stored by the Authentication Manager in the spring security context, which holds the users' authentication information. This information can be accessed throughout the application.&lt;/p&gt;
&lt;h3&gt;
  
  
  UserDetailsService
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--o_eLNSur--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x21ghwtgzk9c3v66uziq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--o_eLNSur--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x21ghwtgzk9c3v66uziq.png" alt="Image description" width="800" height="213"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;UserDetailsService&lt;/strong&gt; interface has only one method &lt;strong&gt;loadUserByUsername&lt;/strong&gt; which takes the username from the authentication object passed down from the filter.&lt;/p&gt;

&lt;p&gt;The loadUserByUsername method returns a &lt;strong&gt;UserDetials&lt;/strong&gt; object which contains user details like username, password, authorities and, other details.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;interface&lt;/span&gt; &lt;span class="nc"&gt;UserDetailsService&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="nc"&gt;UserDetails&lt;/span&gt; &lt;span class="nf"&gt;loadUserByUsername&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;username&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="kd"&gt;throws&lt;/span&gt; &lt;span class="nc"&gt;UsernameNotFoundException&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;interface&lt;/span&gt; &lt;span class="nc"&gt;UserDetails&lt;/span&gt; &lt;span class="kd"&gt;extends&lt;/span&gt; &lt;span class="nc"&gt;Serializable&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="nc"&gt;Collection&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;?&lt;/span&gt; &lt;span class="kd"&gt;extends&lt;/span&gt; &lt;span class="nc"&gt;GrantedAuthority&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;getAuthorities&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;

    &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="nf"&gt;getPassword&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;

    &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="nf"&gt;getUsername&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;

    &lt;span class="kt"&gt;boolean&lt;/span&gt; &lt;span class="nf"&gt;isAccountNonExpired&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;

    &lt;span class="kt"&gt;boolean&lt;/span&gt; &lt;span class="nf"&gt;isAccountNonLocked&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;

    &lt;span class="kt"&gt;boolean&lt;/span&gt; &lt;span class="nf"&gt;isCredentialsNonExpired&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;

    &lt;span class="kt"&gt;boolean&lt;/span&gt; &lt;span class="nf"&gt;isEnabled&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Password Encoder
&lt;/h3&gt;

&lt;p&gt;Since we are talking about security, it is very important that the users' passwords are secured for the entirety of the authentication process. Spring Security comes with some de facto password encoders out of the box. This makes it easier for us developers to manage users while authenticating and storing them in the database.&lt;/p&gt;

&lt;p&gt;Some popular implementations of the PasswordEncoder interface are BCryptPasswordEncoder, SCryptPasswordEncoder, and AbstractPasswordEncoder.&lt;/p&gt;

&lt;p&gt;To work with the password encoder, define a bean that returns a type PasswordEncoder&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Bean&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;PasswordEncoder&lt;/span&gt; &lt;span class="nf"&gt;passwordEncoder&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nf"&gt;BCryptPasswordEncoder&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now you can inject this bean in the user service to encode the password before storing it in the database and in the authentication provider to decrypt the password for validation.&lt;/p&gt;

&lt;p&gt;Knowing and understanding these components of spring security helps to implement security better for our applications.&lt;/p&gt;

&lt;p&gt;If made any mistakes please point it out in the comments.&lt;/p&gt;




&lt;p&gt;Follow me on : &lt;a href="//twitter.com/sohail__shah_"&gt;Twitter&lt;/a&gt;, &lt;a href="//linkedin.com/in/sohailshah20"&gt;LinkedIn&lt;/a&gt;, &lt;a href="//github.com/sohailshah20"&gt;GitHub&lt;/a&gt;, &lt;a href="//linktr.ee/sohailshah20"&gt;Linktree&lt;/a&gt;&lt;/p&gt;

</description>
      <category>spring</category>
      <category>springsecurity</category>
      <category>springboot</category>
      <category>java</category>
    </item>
    <item>
      <title>Persisting non-primitive types in JPA</title>
      <dc:creator>Sohail Shah</dc:creator>
      <pubDate>Sun, 25 Jun 2023 17:16:59 +0000</pubDate>
      <link>https://forem.com/sohailshah/persisting-non-primitive-types-in-jpa-2a3h</link>
      <guid>https://forem.com/sohailshah/persisting-non-primitive-types-in-jpa-2a3h</guid>
      <description>&lt;p&gt;In this post, we'll look at how we can persist non-primitive data types in JPA.&lt;/p&gt;

&lt;p&gt;The primitive data types like int, char, byte, String, boolean, or their respective wrapper classes are mapped automatically by default into the correct database types by implementing ORM frameworks like Hibernate or EclipseLink.&lt;br&gt;
The same is not true for non-primitive data types like Date and Enumeration.&lt;/p&gt;

&lt;p&gt;Let's see how possible solutions to persist them.&lt;/p&gt;
&lt;h2&gt;
  
  
  &lt;strong&gt;Date&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Let's consider an example where we have a Student entity class with a member variable dob(date of birth).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Entity&lt;/span&gt;
&lt;span class="nd"&gt;@Table&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"Student_Table"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Student&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="nd"&gt;@Id&lt;/span&gt;
    &lt;span class="nd"&gt;@GeneratedValue&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;admission_no&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="nd"&gt;@Column&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"student_name"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;age&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;Date&lt;/span&gt; &lt;span class="n"&gt;dob&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The Date here is from the &lt;strong&gt;java.util.Date&lt;/strong&gt; package not &lt;strong&gt;java.sql.Date&lt;/strong&gt; which is a subclass of java.util.Date package. Even though the sql Date is the type that is persisted in the database in the end, util Date type is mostly preferred when working with JPA. The util Date provides a standardized way to work with dates in JPA. The util Date provides date and time with millisecond precision.&lt;/p&gt;

&lt;p&gt;The &lt;a class="mentioned-user" href="https://dev.to/temporal"&gt;@temporal&lt;/a&gt; annotation is used in conjunction with the Date type. The &lt;a class="mentioned-user" href="https://dev.to/temporal"&gt;@temporal&lt;/a&gt; annotation has required a single parameter of type TemporalType. There are three Temporal types &lt;strong&gt;DATE&lt;/strong&gt;, &lt;strong&gt;TIME&lt;/strong&gt;, and &lt;strong&gt;TIMESTAMP&lt;/strong&gt;. Let's look at each one of them.&lt;/p&gt;

&lt;p&gt;Let's annotate the member variable with &lt;a class="mentioned-user" href="https://dev.to/temporal"&gt;@temporal&lt;/a&gt; with &lt;strong&gt;TemporalType&lt;/strong&gt; as &lt;strong&gt;Date&lt;/strong&gt;.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;&lt;em&gt;Check out the previous posts to know how to set up the Java project with JPA and database.&lt;/em&gt;&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Entity&lt;/span&gt;
&lt;span class="nd"&gt;@Table&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"Student_Table"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Student&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="nd"&gt;@Id&lt;/span&gt;
    &lt;span class="nd"&gt;@GeneratedValue&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;admission_no&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="nd"&gt;@Column&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"student_name"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;age&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="nd"&gt;@Temporal&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;TemporalType&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;DATE&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;Date&lt;/span&gt; &lt;span class="n"&gt;dob&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now persisting the student entity in the database.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Main&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt; &lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="nc"&gt;EntityManagerFactory&lt;/span&gt; &lt;span class="n"&gt;entityManagerFactory&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Persistence&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;createEntityManagerFactory&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"myPersistenceUnit"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="nc"&gt;EntityManager&lt;/span&gt; &lt;span class="n"&gt;entityManager&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;entityManagerFactory&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;createEntityManager&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
        &lt;span class="nc"&gt;Student&lt;/span&gt; &lt;span class="n"&gt;student1&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Student&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
        &lt;span class="n"&gt;student1&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setName&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Sohail Shah"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;student1&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setAge&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;18&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;student1&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setAdmission_no&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"1234"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;student1&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setDob&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Date&lt;/span&gt;&lt;span class="o"&gt;());&lt;/span&gt;

        &lt;span class="nc"&gt;EntityTransaction&lt;/span&gt; &lt;span class="n"&gt;transaction&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;entityManager&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getTransaction&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
        &lt;span class="n"&gt;transaction&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;begin&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
        &lt;span class="c1"&gt;//persist the student entity&lt;/span&gt;
        &lt;span class="n"&gt;entityManager&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;persist&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;student1&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;transaction&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;commit&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
        &lt;span class="n"&gt;entityManager&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;close&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
        &lt;span class="n"&gt;entityManagerFactory&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;close&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;strong&gt;TemporalType.DATE&lt;/strong&gt; persists only the date. Now check the database for the values.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--704TNZ9o--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xavcn6jtcw3c48rt8pab.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--704TNZ9o--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xavcn6jtcw3c48rt8pab.png" alt="Image description" width="452" height="84"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;To persist the timestamp we can change the &lt;strong&gt;TemporalType&lt;/strong&gt; to &lt;strong&gt;TIMESTAMP&lt;/strong&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Entity&lt;/span&gt;
&lt;span class="nd"&gt;@Table&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"Student_Table"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Student&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="nd"&gt;@Id&lt;/span&gt;
    &lt;span class="nd"&gt;@GeneratedValue&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;admission_no&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="nd"&gt;@Column&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"student_name"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;age&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="nd"&gt;@Temporal&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;TemporalType&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;TIMESTAMP&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;Date&lt;/span&gt; &lt;span class="n"&gt;dob&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After persisting the student entity, check the database for the values. The date of birth field contains the date with time.&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--a6Ic9Sx0--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/88v8ssrn0eidpxgy3d66.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--a6Ic9Sx0--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/88v8ssrn0eidpxgy3d66.png" alt="Image description" width="539" height="85"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;To persist only the time change the &lt;strong&gt;TemporalType&lt;/strong&gt; to &lt;strong&gt;TemporalType.TIME&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Entity&lt;/span&gt;
&lt;span class="nd"&gt;@Table&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"Student_Table"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Student&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="nd"&gt;@Id&lt;/span&gt;
    &lt;span class="nd"&gt;@GeneratedValue&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;admission_no&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="nd"&gt;@Column&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"student_name"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;age&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="nd"&gt;@Temporal&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;TemporalType&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;TIME&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;Date&lt;/span&gt; &lt;span class="n"&gt;dob&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Persist the student entity and in the database, we can see only the time is persisted.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--1t2-jOPW--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jfi4v8qlenby7k0hm0vb.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--1t2-jOPW--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jfi4v8qlenby7k0hm0vb.png" alt="Image description" width="427" height="80"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Enumeration&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;To persist enumeration values to database columns using JPA is to use the @Enumerated annotation. The @Enumerated annotation tells the JPA to map the enum value to the database.&lt;/p&gt;

&lt;p&gt;Let's add a member variable student type to our student entity which is an enum.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;enum&lt;/span&gt; &lt;span class="nc"&gt;StudentType&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="no"&gt;SCHOLARSHIP&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt;
    &lt;span class="no"&gt;NON_SCHOLARSHIP&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Entity&lt;/span&gt;
&lt;span class="nd"&gt;@Table&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"Student_Table"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Student&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="nd"&gt;@Id&lt;/span&gt;
    &lt;span class="nd"&gt;@GeneratedValue&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;admission_no&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="nd"&gt;@Column&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"student_name"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;age&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="nd"&gt;@Temporal&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;TemporalType&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;TIME&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;Date&lt;/span&gt; &lt;span class="n"&gt;dob&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;StudentType&lt;/span&gt; &lt;span class="n"&gt;studentType&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now annotate the student type member variable with &lt;strong&gt;@Enumerated&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;    &lt;span class="nd"&gt;@Enumerated&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;StudentType&lt;/span&gt; &lt;span class="n"&gt;studentType&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That's it, now we can persist the student entity and check the database.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;        &lt;span class="nc"&gt;Student&lt;/span&gt; &lt;span class="n"&gt;student1&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Student&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
        &lt;span class="n"&gt;student1&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setName&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Sohail Shah"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;student1&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setAge&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;18&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;student1&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setAdmission_no&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"1234"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;student1&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setDob&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Date&lt;/span&gt;&lt;span class="o"&gt;());&lt;/span&gt;
        &lt;span class="n"&gt;student1&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setStudentType&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;StudentType&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;SCHOLARSHIP&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Q670Py_4--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/02p83i054h31j7y286fo.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Q670Py_4--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/02p83i054h31j7y286fo.png" alt="Image description" width="548" height="80"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The value of student type in the database column is set to 0. That's because by default enum type is set to ordinal. When enum type is set to ordinal, JPA persists the position of the enum in the enum class. In our example, The StudentType enum class has two constant strings, SCHOLARSHIP with position 0 and NON_SCHOLARSHIP with position 1. Since we set the student type to StudentType.SCHOLARSHIP it's position was persisted.&lt;/p&gt;

&lt;p&gt;This behaviour can be changed by setting the &lt;strong&gt;EnumType&lt;/strong&gt; as String in the &lt;strong&gt;@Enumerated&lt;/strong&gt; annotation parameter. Let's do it now.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;    &lt;span class="nd"&gt;@Enumerated&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;EnumType&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;STRING&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;StudentType&lt;/span&gt; &lt;span class="n"&gt;studentType&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now persist the student entity and check the database.&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--T_HNlIVN--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z12w3pzeg7eifcxuhp3v.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--T_HNlIVN--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z12w3pzeg7eifcxuhp3v.png" alt="Image description" width="545" height="87"&gt;&lt;/a&gt;&lt;br&gt;
The actual value of the string is saved to the database.&lt;br&gt;
Use the enum type in annotation parameter as per your needs, either as &lt;strong&gt;EnumType.STRING&lt;/strong&gt; or &lt;strong&gt;EnumType.ORDINAL&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;But be careful with using enum in your entities. If the enum type is set to ordinal, you cannot change the positions of constant strings in the enum class. If the enum type is set to string then you can change the position but cannot change the spellings of it. Doing both will lead to data inconsistencies in the database.&lt;/p&gt;




&lt;p&gt;Follow me on : &lt;a href="//twitter.com/sohail__shah_"&gt;Twitter&lt;/a&gt;, &lt;a href="//linkedin.com/in/sohailshah20"&gt;LinkedIn&lt;/a&gt;, &lt;a href="//github.com/sohailshah20"&gt;GitHub&lt;/a&gt;, &lt;a href="//linktr.ee/sohailshah20"&gt;Linktree&lt;/a&gt;&lt;/p&gt;

</description>
      <category>java</category>
      <category>jpa</category>
      <category>hibernate</category>
    </item>
    <item>
      <title>Know The JPA Persistence.xml File</title>
      <dc:creator>Sohail Shah</dc:creator>
      <pubDate>Wed, 21 Jun 2023 07:01:32 +0000</pubDate>
      <link>https://forem.com/sohailshah/know-the-jpa-persistencexml-file-41ei</link>
      <guid>https://forem.com/sohailshah/know-the-jpa-persistencexml-file-41ei</guid>
      <description>&lt;p&gt;In the previous posts, we set up the Java project and connected it to a database with JPA, and hibernate. Let's look back on the persistence.xml file we created and understand it in more detail.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;The location of this file is src -&amp;gt; META-INF -&amp;gt; persistence.xml&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
 XML
&amp;lt;?xml version="1.0" encoding="UTF-8"?&amp;gt;
&amp;lt;persistence xmlns="http://java.sun.com/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
             version="2.0"&amp;gt;
    &amp;lt;persistence-unit name="myPersistenceUnit" transaction-type="RESOURCE_LOCAL"&amp;gt;
        &amp;lt;properties&amp;gt;
            &amp;lt;!-- Database connection properties --&amp;gt;
            &amp;lt;property name="javax.persistence.jdbc.url" value="jdbc:h2:tcp://localhost/~/test"/&amp;gt;
            &amp;lt;property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/&amp;gt;
            &amp;lt;property name="javax.persistence.jdbc.user" value="sa"/&amp;gt;
            &amp;lt;property name="javax.persistence.jdbc.password" value=""/&amp;gt;

            &amp;lt;!-- Hibernate properties --&amp;gt;
            &amp;lt;property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/&amp;gt;
            &amp;lt;property name="hibernate.show_sql" value="true"/&amp;gt;
            &amp;lt;property name="hibernate.format_sql" value="true"/&amp;gt;
            &amp;lt;property name="hibernate.hbm2ddl.auto" value="create"/&amp;gt;
        &amp;lt;/properties&amp;gt;
    &amp;lt;/persistence-unit&amp;gt;
&amp;lt;/persistence&amp;gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The main node/ tag is the &lt;strong&gt;&amp;lt;persistence&amp;gt;&lt;/strong&gt; &amp;amp; everything goes inside it.&lt;/p&gt;

&lt;p&gt;The next node is &lt;strong&gt;&amp;lt;persistence-unit&amp;gt;.&lt;/strong&gt; We can create multiple persistence-unit nodes inside the persistence node. Each persistence-unit node has its name and transaction type. In our case the name is "myPersistenceUnit" and the transaction type is set to RESOURCE_LOCAL.&lt;/p&gt;

&lt;p&gt;There are typically three types of transactions&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;JTA (Java Transaction API) - used in Java EE environments&lt;/li&gt;
&lt;li&gt;RESOURCE_LOCAL             - used in Java SE environments&lt;/li&gt;
&lt;li&gt;AUTO                       - determines the environment automatically&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Next is defining the properties of our persistence unit. First, we have provided the database connection properties. Let's look at them individually.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;url&lt;/strong&gt; - It is the database connection string&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
 XML
&amp;lt;property name="javax.persistence.jdbc.url" value="jdbc:h2:tcp://localhost/~/test"/&amp;gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;driver&lt;/strong&gt; - The database driver for the respective database used in the application&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
 XML
&amp;lt;property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/&amp;gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;user&lt;/strong&gt; - username for the database connection&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
 XML
&amp;lt;property name="javax.persistence.jdbc.user" value="sa"/&amp;gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;password&lt;/strong&gt; - password for the database connection&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
 XML
&amp;lt;property name="javax.persistence.jdbc.password" value=""/&amp;gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;All the properties come from the javax.persistence meaning these are JPA property names, not the hibernate properties.&lt;/p&gt;

&lt;p&gt;Next, we have defined the hibernate properties. These properties define the working behavior of the hibernate implementation. Let's look at them individually.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Dialect :&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The dialect here means the SQL query grammar used by the JPA implementation uses when connecting to the database. Even though all the databases use SQL, there are some minor differences in the grammar. So we have to specify the dialect for the database we are using.&lt;/p&gt;

&lt;p&gt;For example, if we are using PostgreSQL we set the dialect like this&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
 XML
&amp;lt;property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/&amp;gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;For MySQL database&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
 XML
&amp;lt;property name="hibernate.dialect" value="org.hibernate.dialect.MYSQLDialect"/&amp;gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;show_sql :&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;If this property is set to true when we run our application and make database operations we can actually see the SQL queries written in the console. This is useful mainly for development purposes&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F51ta3myffy3l6m52zoye.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F51ta3myffy3l6m52zoye.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;format-sql :&lt;/strong&gt;&lt;br&gt;
If this property is set to true, then it formats the SQL queries in the console. Again this can be useful for development purposes.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
 XML
 &amp;lt;property name="hibernate.format_sql" value="true"/&amp;gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;hbm2ddl&lt;/strong&gt;&lt;strong&gt;.&lt;/strong&gt;&lt;strong&gt;auto :&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This property defines the auto behaviour of the hibernate when converting JPA entities to ddl (data definition language). Here it is set to create-drop which sets the behaviour to drop the database schema and tables and create new schemas based on the JPA entities. It is typically used in development only as we don't want to drop our existing tables from the database.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
 XML
&amp;lt;property name="hibernate.hbm2ddl.auto" value="create"/&amp;gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Some different behaviours we can set the auto to are:&lt;/p&gt;

&lt;p&gt;i. &lt;strong&gt;validate&lt;/strong&gt; - Validates the schema against the mapping metadata&lt;br&gt;
ii. &lt;strong&gt;update&lt;/strong&gt; - Updates the schema based on the mapping metadata&lt;br&gt;
iii. &lt;strong&gt;create&lt;/strong&gt; - Creates a new schema from scratch based on the mapping metadata&lt;br&gt;
iv. &lt;strong&gt;none&lt;/strong&gt; - Disables automatic schema generation and update&lt;/p&gt;

&lt;p&gt;There are many other properties and tags present which can be used to define the behaviour of our persistence unit, but these are enough to get started with your application running.&lt;/p&gt;




&lt;p&gt;Follow me on : &lt;a href="//twitter.com/sohail__shah_"&gt;Twitter&lt;/a&gt;, &lt;a href="//linkedin.com/in/sohailshah20"&gt;LinkedIn&lt;/a&gt;, &lt;a href="//github.com/sohailshah20"&gt;GitHub&lt;/a&gt;, &lt;a href="//linktr.ee/sohailshah20"&gt;Linktree&lt;/a&gt;&lt;/p&gt;

</description>
      <category>java</category>
      <category>jpa</category>
      <category>hibernate</category>
    </item>
  </channel>
</rss>
