JimmyD
JimmyD

Reputation: 2759

Spring boot generates wrong sql code

I'm creating a POC for using Spring boot with my next project. Now I created a rest service that wil query all the data from a MS sql server database.

The entity that I want to query looks like:

@Entity
@Table(name = "Item", schema = "materialManagement", uniqueConstraints = @UniqueConstraint(columnNames = {
        "companyID", "number" }))
public class Item implements java.io.Serializable {
//all variabels are placed here
}

Now when I create a repository for the Item class:

public interface NoteRepository extends JpaRepository<Item, Long> {
}

In my controller I autowire the repo and query the repo with findAll():

@RestController
@RequestMapping("/api")
public class NoteController {
 @Autowired
    NoteRepository noteRepository;

    @GetMapping("/notes")
    public List<Item> getAllNotes() {
        return noteRepository.findAll();
    }
}

Now when I send a request to the controller I got following error:

com.microsoft.sqlserver.jdbc.SQLServerException: Invalid object name 'material_management.item'.

In the database there is indeed no material_management schema only materialManagement. But from where does that generated schema come from?

My application.properties looks like:

> spring.datasource.url =
> jdbc:sqlserver://localhost:1433;databaseName=CR_ApplicationSuite;integratedSecurity=true;
> 
> spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
> ## Hibernate Properties
> 
> # The SQL dialect makes Hibernate generate better SQL for the chosen database spring.jpa.properties.hibernate.dialect =
> org.hibernate.dialect.SQLServer2008Dialect

Upvotes: 0

Views: 2252

Answers (2)

JimmyD
JimmyD

Reputation: 2759

I added following lines to the 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

Upvotes: 5

Simon Martinelli
Simon Martinelli

Reputation: 36223

The Hibernate naming strategy replaces camel case with _

In your case:

@Table(name = "Item", schema = "materialManagement", ...

Becomes

material_management

Solution

Either remove the camel case with all lower case or if it must be camel case you must change the Hibernate naming strategy.

Application properties:

spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.EJB3NamingStrategy

Upvotes: 1

Related Questions