Sobes.tech
Junior — Middle

What annotations in Spring are used for database interaction?

sobes.tech AI

Answer from AI

In Spring, the following main annotations are used for database interaction:

  • @Entity — marks a class as an entity that will be mapped to a database table.
  • @Table — specifies the table name and other parameters for the entity.
  • @Id — indicates the field that is the primary key.
  • @GeneratedValue — defines the strategy for generating the primary key value.
  • @Column — configures the mapping of a field to a table column.
  • @Repository — marks a class as a data access component (DAO), allowing Spring to handle database exceptions.
  • @Transactional — manages transactions when working with the database.

Example:

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

    @Column(nullable = false)
    private String name;

    // getters and setters
}