Home > OS >  Difference between @Entity and @Table in Spring boot . Do we need both?
Difference between @Entity and @Table in Spring boot . Do we need both?

Time:03-09

Do we need both annonation for a model class? What is the difference between @Entity and @Table

@Entity
@Table(name = "widget") // do we need this??
public class WidgetEntity {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;
  private String clientName;
}

CodePudding user response:

You need @Entity but @Table is an optional annotation that you can override default table name, schema name etc.

CodePudding user response:

If you are planning some class to be scanned and looked as an entity by Hibernate it must has @Entity annotation. Now since Hibernate is Object-Relational Mapping tool, which means that it is a bridge between objects and the database when you put

@Entity <-- this is an entity class that you will work with
@Table(name = "widget") <-- and this is a corresponding table that matches that entity in the database

Similar thing goes for

@Column(name="clientName")<-- this is a value from your database field that will correspond with your entity field
private String clientName <-- this is your entity field

When using hibernate you need to explain in the class both of the worlds, the SQL world and the Java Hibernate world.

  • Related