Annotates a class as an entity, representing a persistent class corresponding to a database structure.
Entity classes must adhere to specific rules:
- At least one field must be annotated with
Id
orColumn
. - Constructors must be
public
orprotected
with no parameters, or with parameters annotated withColumn
orId
. - Annotations at the constructor will build the entity and read information from the database, while field annotations are required to write information to the database.
- If both a non-args constructor and a constructor with annotated parameters exist, the constructor with annotations will be used to create the entity.
- Constructor parameters without annotations will be ignored, utilizing a non-arg constructor instead.
- Entities should not have multiple constructors using
Id
orColumn
annotations. - Record classes can also serve as entities.
Enums or interfaces cannot be designated as entities.
Each entity must have a unique identifier, typically annotated with Id
.
The following example demonstrates two classes, Person
and Address
, where a person has an address:
@Entity
public class Person {
@Id
private Long id;
@Column
private String name;
@Column
private Address address;
}
@Embeddable
public class Address {
@Column
private String street;
@Column
private String city;
}
Note: NoSQL databases may have varying behaviors regarding serialization, resulting in different storage formats based on the NoSQL vendor.
The sample below demonstrates the use of records as entities:
@Entity
public record Person(@Id Long id, @Column String name, @Column Address address) {
}
@Embeddable
public class Address {
@Column
private String street;
@Column
private String city;
public Address(@Column String street, @Column String city) {
this.street = street;
this.city = city;
}
}
- Since:
- 1.0
- See Also:
-
Optional Element Summary
Optional Elements
-
Element Details
-
value
String valueThe name of the entity. If not specified, defaults to the unqualified simple name of the class. This name is used to refer to the entity in queries and also to represent the name in the NoSQL database structure, such as the table name or collection name.For example, given the class
org.jakarta.nosql.demo.Person
, the default name will bePerson
.To customize the name, set the value of the
@Entity
annotation to the desired name, as shown below:@Entity("ThePerson") public class Person { }
- Returns:
- the entity name (optional)
- Default:
""
-