Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the default format of JPA generated column names

Currently I'm mapping new JPA entities to an old database. The column names in the database have column names separated with underscore like 'my_column_name'.

The problem is that JPA defaults to using with camel case.

// Will be 'myColumnName' in queries and generated databases
private String myColumnName;

I know it's possible to add @Column(name="..") or @JoinColumn(name="...") on the properties - but that means i have to add it to every single property in all entities.

@Column(name = "my_column_name")
private String myColumnName;

Is it possible to change the default behavior of JPA to use 'my_column_name' instead of 'myColumnName'?

like image 779
Tomas F Avatar asked Oct 29 '14 00:10

Tomas F


People also ask

Which annotation is a default annotation in JPA?

The @Basic annotation has two attributes, optional and fetch. Let's take a closer look at each one. The optional attribute is a boolean parameter that defines whether the marked field or property allows null. It defaults to true.

Is @column mandatory in JPA?

@Column. Let's start with the @Column annotation. It is an optional annotation that enables you to customize the mapping between the entity attribute and the database column.

What is @column annotation in spring boot?

Spring Boot is a microservice-based framework and making a production-ready application in it takes very little time. In this article, we will discuss how to change the column name in the Spring project using JPA. @Column annotation is used for Adding the column the name in the table of a particular MySQL database.


3 Answers

Add the following lines to your application.properties :

spring.jpa.hibernate.naming.implicit-strategy=
   org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl
spring.jpa.hibernate.naming.physical-strategy=
   org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

According to the following link, I tested and it worked:

Spring Boot + JPA : Column name annotation ignored

like image 164
Hubert Avatar answered Oct 25 '22 10:10

Hubert


Unfortunately JPA doesn't provide any global naming strategy. So you should use @Column annotation on each property. But you can use Hibernate to achive this goal. See Hibernate documentation.

like image 38
njjnex Avatar answered Oct 25 '22 09:10

njjnex


You need to investigate Implementing a NamingStrategy

like image 1
Steve C Avatar answered Oct 25 '22 10:10

Steve C