top of page
hand-businesswoman-touching-hand-artificial-intelligence-meaning-technology-connection-go-

Spring JPA Entity Mappings for beginners !

Part 2 : Implementing a mapping in Springboot JPA


Figuring out the relation between tables:

Step 1 : Go through the Requirement Document / Design Document and understand the functionality and related tables.

Step 2 : You can confirm the relation with ER Diagram

Database has an option to generate ER Diagram.

This is how we generate in Postgress DB :

Select the Database; Right click on it; in the popup Menu click

‘Generate ERD’

Step 3 : Check the costraints on both/all the tables.

Good!.. You know the relation now.


What is Entity Mapping ?

You create an Entity Object which represents a row in your Database table.

When you do so, you also specify the relation between two tables.

Implementing the relation between two Entity Objects is what is called as mapping.

When you create an Entity Object , instead of providing a regular field for foriegnkey we will provide the Entity Reference of the linked Entity.

Mapping can be uni-directional or bi-directional.

If only one entity in a relation has reference to another entity, it is uni-directional.

If both has reference to each other it is bi-directional.


Lets see How to implement a uni-directional mapping between Batch & Program Entities :

Following the above steps, Now you know that Program table is parent and Batch is child;

Conceptually one Program has multiple batches under it.

And Batch has a ‘Many to One’ mapping with Program.

So when u implement Batch Entity , instead of the foreignkey field ‘batch_program_id’ we will have a reference to Program Entity with @ManyToOne Annotation. With @JoinColumn annotation, we should provide foriegnkey column name ie, ‘batch_program_id’


     @Entity 
     @Table ( name = "batch" ) 
     public class Batch {
         @Id 
         @GeneratedValue ( strategy = GenerationType.SEQUENCE,    
                           generator = "batch_id_seq" )
         @SequenceGenerator( name="batch_id_seq", 
							 sequenceName = "batch_batch_id_seq", 
							 allocationSize = 1)
         @Column( name = "batch_id" )
         private Integer batchId;

         @Column( name = "batch_name" )
         private String batchName;
       
         @Column( name = "batch_description" )
         private String batchDescription;

         @ManyToOne 
         @JoinColumn ( name = "batch_program_id", nullable = false )
         private Program program;   
                                              
         // getter setters, constructors... 
    }

     @Entity
     @Table(name="program")  
     public class Program {
	    @Id
	    @GeneratedValue ( strategy = GenerationType.SEQUENCE, 
	          generator = "program_id_seq" )
	    @SequenceGenerator( name="program_id_seq", 
				sequenceName = "program_program_id_seq", 
				allocationSize = 1)           
	    @Column(value="program_id")
        private Integer programId;

	    @Column(value="program_name")
	    private String programName;

	    @Column(value="program_description")
        private String programDescription;
                                                        
		// getter setters, constructors... 
    }

Now Batch Entity is joined/linked with Program Entity.

It is the same as joining 2 tables with an SQL query.

When u get Batch records now, Hibernate will also load data of Program under which Bach was created.


      {
         "batch_id": 4,
         "batch_name": "04",
         "batch_description": "BATCH 04",
         "program": {
            "program_id": 1,
            "program_name": ".NET"
            "program_description": ".NET Course"         
          }         
     }

Creating/updating a Batch Record :

When you create a new Batch Entity Object ie, you create a new record in Batch table, as you have program reference , you need to find the Program reference for the programId under which this Batch will be created and set it in Batch Object.


     Program program = programRepository.findById( programId )
              .orElseThrow( ()->new RuntimeException("ProgramId:" +                           programId + " not available; Please give an existing ProgramId" ));
       
     batch.setProgram(program);
     batchRepository.save(batch);   

This will create a new Row in Batch table with batch_program_Id set to whatever programId is there in the program reference you have set. Yes, that’s it.

While updating, if you want to update the current batch to a different program, again you need to find the reference of that program and set it in batch.


Deleting a Batch Record :

In Entity mapping, we can use CascadeType.REMOVE. When a parent reference is deleted it would delete all child references. Please note we should avoid CascadeType.REMOVE for to-many associations.

    @ManyToOne ( fetch = FetchType.LAZY , cascade = CascadeType.REMOVE)  )        
    @JoinColumn ( name = "batch_program_id", nullable = false )                            
    private Program program;    

Happy reading !..



449 views0 comments

Recent Posts

See All
bottom of page