In this tutorial, we will learn crud operations in spring boot with Mysql
If you want to learn more about connecting MySQL from spring boot, please follow this link https://beginnersbug.com/connect-mysql-database-from-spring-boot/
What you’ll learn
End of this tutorial, you will learn crud operations in spring boot with Mysql
Save syntax
Select all syntax
Select by id syntax
Delete all syntax
Delete by id syntax
Database Scripts
Model Class
JpaRepository
Here I am using JpaRepository to achieve CRUD Operations easily. JpaRepository have inbuilt function like findAll,findById,save,delete,deleteById
StudentDao
You need to extend JpaRepository in your dao class with Entity class as like below
Here my Entity class is Students.java and Primary Key variable is Long
Controller Class
In the above controller class, We are calling findAll, findById, save, delete, deleteById methods for CRUD Operations
Advantage of using JpaRepository
you don’t need to write any query or any methods, all are inbuilt in JpaRepository class
Exceptions
java.sql.SQLException: Field ‘id’ doesn’t have a default value
You will have chance to get above exception while implementing. Make sure below things
You should have below annotation in the model class @GeneratedValue(strategy=GenerationType.IDENTITY)
And also make sure your table has primary key & auto_increment parameter
org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save()
Make sure your model class have <span class="token annotation punctuation">@id</span>
and <span class="token annotation punctuation">@GeneratedValue</span><span class="token punctuation">(</span>strategy <span class="token operator">=</span> <span class="token class-name">GenerationType</span><span class="token punctuation">.</span>IDENTITY<span class="token punctuation">)</span>
Github
https://github.com/rkumar9090/student-service
Related Articles
connect MySQL database from spring boot