5

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;
}
Mustafa
  • 1,738
  • 2
  • 24
  • 34
  • 1
    The table annotation here is giving information about the table, specifically its name. – khelwood Mar 08 '22 at 22:13
  • 1
    @Entity annotation defines that a class can be mapped to a table; @Table annotation allows you to specify the details of the table that will be used to persist the entity in the database. In this case with `@Table(name = "widget")` you override the default name of the table (the class name) – rentox98 Mar 08 '22 at 22:15

2 Answers2

4

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

bjorke07
  • 94
  • 1
  • 10
3

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.

zawarudo
  • 1,907
  • 2
  • 10
  • 20
  • I see. I like when you use the words "In both of the worlds" . It makes sence. takes abit of time to understand when you come from javascript and firebase world haha. @zawarudo – Mustafa Mar 08 '22 at 22:48
  • It seems like a lot of work, but once you set your entity properly, you can enjoy the fruits of creating an object and do .save() or .persist() and the object is in your database. – zawarudo Mar 08 '22 at 22:50