Performance: JPA entity with @Entity annotation
This affects the initial loading and runtime performance of database interactions in a Spring Boot application.
Jump into concepts and practice - no test required
import jakarta.persistence.Entity; import jakarta.persistence.Id; @Entity public class User { @Id private Long id; private String name; private int age; }
import jakarta.persistence.Entity; import jakarta.persistence.Id; @Entity public class User { private String name; private int age; }
| Pattern | Entity Recognition | Query Efficiency | Memory Usage | Verdict |
|---|---|---|---|---|
| Missing @Id annotation | Fails to identify primary key | Queries fail or are inefficient | Higher due to improper caching | [X] Bad |
| Proper @Entity with @Id | Correct primary key mapping | Optimized queries with indexing | Lower due to effective caching | [OK] Good |
@Entity annotation in a Spring Boot application?@Entity@Entity annotation tells Spring Boot and JPA that this class represents a table in the database.@RestController or @Service serve different purposes unrelated to database tables.@Entity marks database tables [OK]@Entity means database table class [OK]@Entity with @Service@Entity creates REST endpoints@Entity configures app settings@Entity annotation@Entity to be recognized as a JPA entity.@Id on a field@Id to map the primary key.@Entity and @Id on ID field [OK]@Entity annotation@Id on the ID field@Service instead of @Entity@Entity
public class Product {
@Id
private Long id;
private String name;
public Product() {}
public Product(Long id, String name) {
this.id = id;
this.name = name;
}
public String getName() { return name; }
}Product with id=1 and name="Book" using JPA repository and then retrieve it?@Entity class and its fields to save and load data. The constructor and getter allow access to fields.name will be loaded correctly.@Entity
public class Customer {
private Long id;
private String email;
public Long getId() { return id; }
public String getEmail() { return email; }
}@Entity annotation@Entity, so it is recognized as an entity.@Id annotationid field lacks @Id, so JPA cannot identify the primary key, causing errors.@Id annotation on the id field -> Option D@Id on primary key [OK]@Id on the primary key field [OK]@Id annotationOrder with a composite primary key made of orderId and productId. Which approach correctly applies the @Entity annotation and primary key setup?@Embeddable to represent composite keys.@EmbeddedId in the entity@EmbeddedId to include the composite key class as its primary key.@Entity on Order and create a separate @Embeddable class for the composite key with @EmbeddedId in Order -> Option A