How to generate a primary key using @GeneratedValue

In JPA, you can use @GeneratedValue to automatically generate a unique value for the primary key and apply it to a filled with @ Id. There are four ways to generate the value of this primary key. ・ GenerationType.IDENTITYGenerationType.SEQUENCEGenerationType.TABLEGenerationType.AUTO I examined the difference between each DBMS.

Verification environment

GenerationType.IDENTITY Use the identity column of the table to generate the primary key value.

@Entity
@Table(name="users")
public class User implements Serializable {
	
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name="userid")
	private long userId;
	
	@Column(name="username")
	private String userName;
	
	@Column(name="password")
	private String password;
	
	@Column(name="email")
	private String email;
        
	...
}

For PostgreSQL, the column type of the associated table must be SERIAL.

CREATE TABLE users
(
    userid serial NOT NULL,
    username character varying,
    password character varying,
    email character varying,
    CONSTRAINT "PK" PRIMARY KEY (userid)
)

For MySQL, you need to specify AUTO_INCREMENT for the column attribute.

Create TABLE users (
    userid bigint not null AUTO_INCREMENT PRIMARY KEY,
    username varchar(20),
    password varchar(20),
    email varchar(20)
);

Oracle does not support GenerationType.IDENTITY.

GenerationType.SEQUENCE Use the database sequence object to generate the primary key value.

@Entity
@Table(name="users")
public class User implements Serializable {
	
	@Id
	@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "userid_seq")
	@SequenceGenerator(name = "userid_seq", sequenceName = "userid_seq", allocationSize = 1)
	@Column(name="userid")
	private long userId;
	
	@Column(name="username")
	private String userName;
	
	@Column(name="password")
	private String password;
	
	@Column(name="email")
	private String email;
        
	...
}

For PostgreSQL, the sequence object specified in sequenceName is required.

CREATE SEQUENCE userid_seq
    INCREMENT 1
    MINVALUE 1
    MAXVALUE 10000
    START 1
    CACHE 1
    CYCLE;

You cannot use GenerationType.SEQUENCE because MySQL does not support sequences.

Like PostgreSQL, Oracle requires a specified sequence object.

create sequence "USERID_SEQ"
    start with 1
    increment by 1
    maxvalue 10000
    minvalue 1
    nocache
    cycle
    noorder

GenerationType.TABLE Generates a primary key value using a table that holds the primary key value.

@Entity
@Table(name="users")
public class User implements Serializable {
	
	@Id
	@TableGenerator( name = "seqTable", table = "seq_table", pkColumnName = "seq_name", pkColumnValue = "user_seq", valueColumnName = "seq_value", initialValue = 1, allocationSize = 1 )
	@GeneratedValue(strategy = GenerationType.TABLE, generator="seqTable")
	@Column(name="userid")
	private long userId;
	
	@Column(name="username")
	private String userName;
	
	@Column(name="password")
	private String password;
	
	@Column(name="email")
	private String email;
        
	...
}

PostgreSQL, MySQL and Oracle are all compatible and you need to create the specified table object.

--postgresql
CREATE TABLE seq_table
(
    seq_name character varying NOT NULL,
    seq_value bigint,
    CONSTRAINT seq_pk PRIMARY KEY (seq_name)
)

GenerationType.AUTO Select a different method for each database to generate a primary key value.

@Entity
@Table(name="users")
public class User implements Serializable {
	
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	@Column(name="userid")
	private long userId;
	
	@Column(name="username")
	private String userName;
	
	@Column(name="password")
	private String password;
	
	@Column(name="email")
	private String email;
        
	...
}

For PostgreSQL, use the sequence object hibernate_sequence. If this sequence does not exist, you will receive the error message ʻorg.postgresql.util.PSQLException: ERROR: Relation "hibernate_sequence" does not exist`.

For MySQL, it works the same as GenerationType.IDENTITY. If AUTO_INCREMENT is not specified for the column attribute, the error message java.sql.SQLException: Field'userid' doesn't have a default value is displayed.

For Oracle, as with PostgreSQL, the sequence object hibernate_sequence is used.

Recommended Posts

How to generate a primary key using @GeneratedValue
How to sort a List using Comparator
[Rails] How to create a graph using lazy_high_charts
How to delete a controller etc. using a command
[Ruby] How to generate a random alphabet string
How to automatically generate a constructor in Eclipse
[Swift] How to generate an ID to uniquely identify a certain thing (using UUID)
How to use an array for a TreeMap key
How to manually generate a JWT with Rails Knock
How to delete custom Adapter elements using a custom model
How to convert A to a and a to A using AND and OR in Java
[Ruby/Rails] How to generate a password in a regular expression
[Rails] How to install a decorator using gem draper
How to leave a comment
How to insert a video
How to create a method
How to authorize using graphql-ruby
How to use a foreign key with FactoryBot ~ Another solution
How to output array values without using a for statement
How to join a table without using DBFlute and sql
How to register as a customer with Square using Tomcat
How to add columns to a table
How to make a Java container
How to sign a Minecraft MOD
How to make a JDBC driver
[Java] How to create a folder
How to make a splash screen
How to make a Jenkins plugin
How to make a Maven project
How to make a Java array
How to build CloudStack using Docker
How to create a jar file or war file using the jar command
How to make a hinadan for a Spring Boot project using SPRING INITIALIZR
How to run a mock server on Swagger-ui using stoplight/prism (using AWS/EC2/Docker)
[Rails 6] How to create a dynamic form input screen using cocoon
How to rename a model with foreign key constraints in Rails
How to make a groundbreaking diamond using Java for statement wwww
[Xcode] How to add a README.md file
How to make a Java calendar Summary
A memorandum on how to use Eclipse
How to redo a deployment on Heroku
How to return a value from Model to Controller using the [Swift5] protocol
How to implement a slideshow using slick in Rails (one by one & multiple by one)
[Rails] How to upload images using Carrierwave
How to create a query using variables in GraphQL [Using Ruby on Rails]
How to build a Ruby on Rails environment using Docker (for Docker beginners)
[Basic] How to write a Dockerfile Self-learning ②
How to insert a video in Rails
[Java] How to calculate age using LocalDate
How to add a new hash / array
[Introduction to Java] How to write a Java program
How to create a Maven repository for 2020
How to make a Discord bot (Java)
[Java] How to get to the front of a specific string using the String class
How to print a Java Word document
[Swift5] How to create a splash screen
[rails] How to create a partial template
How to delete data with foreign key
[Swift5] How to implement animation using "lottie-ios"
How to SSH into Ubuntu from a terminal with public key authentication
How to implement image posting using rails