Issue
I have this piece of code where the author creates a JPA Entity. Somehow, it's successfully working and that seems weird to me since not every field is annotated with "@Column". Based on that, here's my question:
How it is possible for this class to work properly (all data is being successfully recorded in the database) without every field not having a "Column" annotation (excepting "id")?
/**
* @author Ram Alapure
* @since 05-04-2017
*/
@Entity
@Table(name="User")
public class User {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "id", updatable = false, nullable = false)
private long id;
private String firstName;
private String lastName;
private LocalDate dob;
private String gender;
private String role;
private String email;
private String password;
@Override
public String toString() {
return "User [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", dob=" + dob + ", email="
+ email + "]";
}
}
For instance, here's another class which is working properly as well. But this time, with a "@Column" annotation in every field. I thought it was a pre-requisite to JPA create a column from the field.
@Entity
@Table(name = "address")
public class Address {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "address_id")
private long id;
@Column(name = "rua")
private String street;
@Column(name = "number")
private int number;
@Column(name = "complement")
private String complement;
@Column(name = "suburb")
private String suburb;
@Column(name = "city")
private String city;
@Column(name = "state")
private String state;
@Column(name = "country")
private String country;
@Column(name = "cep")
Getters and Setters were hidden from all pieces of code since they just look like regular getters and setters, not being necessary to be shown.
Solution
If you don't specify @Column annotation (Optional) then Hibernate uses default naming stretegy by using camel case.
firstName field becomes first_name column in Database.
You can also define your own naming stretegy according to your needs.
From the documentation.
strategy ; Hibernate 5 defines a Physical and Implicit naming strategies. Spring Boot configures SpringPhysicalNamingStrategy by default. This implementation provides the same table structure as Hibernate 4: all dots are replaced by underscores and camel cases are replaced by underscores as well.
Answered By - Alien