Entity?

  • JPA Entity is a Java Class that is mapped to a table in the database

 

Example

@Entity
@Table(name = "users")
public class User {
	@Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    @Column(name = "username")
    private String name;
    
    @Column
    private String phone;
}

SQL query ran
table created in H2 database

Annotations

@Entity

  • Specifies that this class is an entity

@Table

  • Specifies the primary table for the annotated entity.
  • Without this annotation, JPA entity is mapped to a table named entity's name
  • We can specify additional tables with @SecondaryTable annotation.

@Column

  • Specifies the mapped column for a persistent property or field
  • We can specify properties of the column (name, nullable, etc)

@Id

  • Specifies the primary key of an entity
  • with @GeneratedValue, the database will automatically assign primary key based on the strategy selected

@GeneratedValue

  • GenerationType.AUTO
    • Default generation type
    • Let the persistence provider (ex Hibernate) choose the generation strategy
  • GenerationType.IDENTITY
    • Relies on an auto-incremented database column and lets the database generate a new value with each INSERT operation
  • GenerationType.SEQUENCE
    • Uses a database sequence to generate unique values
    • Requires @SequenceGenerator annotation to define the generator
    • Sequence: database object which allows the automatic generation of the values
    • Can be used for database that supports sequence: Oracle, PostgreSQL, H2, etc
  • GenerationType.TABLE
    • Requires @TableGenerator annotation
    • Similar to SEQUENCE, but creates a table that is only used for key generation
    • Rarely used nowadays

'Spring' 카테고리의 다른 글

Spring Boot Exception Handling  (0) 2023.09.14
DTO (Data Transfer Object)  (0) 2023.09.14
Spring Data JPA Repository  (0) 2023.09.01
Spring vs Spring Boot  (0) 2023.08.30
JPA and ORM  (0) 2023.08.30

+ Recent posts