I am new in Spring Boot
and such things, this is the first project I was trying to explore and was following a lecture for project creation, I made an entity class with @Entity
and @Table
annotations, when I executed the project, two table in mysql
db got created namely blog
and blog_seq
, I want to understand how this blog_seq
got created and what is the significance to this table.
Entity
class:
package com.SpringBoot.blog.entity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import jakarta.persistence.UniqueConstraint;
@Entity
@Table(name = "posts", uniqueConstraints = {@UniqueConstraint(columnNames = {"titles"})})
public class Posts {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
@Column(name = "titles", nullable = false)
private String title;
@Column(name = "description", nullable = false)
private String description;
@Column(name = "content", nullable = false)
private String content;
public Posts() {
super();
}
public Posts(long id, String title, String description, String content) {
super();
this.id = id;
this.title = title;
this.description = description;
this.content = content;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
application.properties
:
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/blog
spring.datasource.userName=root
spring.datasource.password=123456789
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
mysql
workbench:
Thanks for the help!!
Tried changing the entity annotations and application.properties
somewhat, but not working.
It basically happened due to:
@GeneratedValue(strategy=GenerationType.AUTO)
AUTO
strategy uses the database sequence to generate the unique value for your id column. If you log SQL queries then you would be able to see an extra query against that blog_seq
to select the next unique value.
If that is not what you expect then you can use:
@GeneratedValue(strategy=GenerationType.IDENTITY)
It will use the database auto-increment
id column and let the database generate next value for your id column.
It might not matter a lot for your project but do read about the performance implications of these two strategies.
Edit:
Found this article which explains these strategies nicely. It will help you.
https://thorben-janssen.com/jpa-generate-primary-keys/