Как исправить «com.microsoft.sqlserver.jdbc.SQLServerException: неверное имя столбца« taxi_id »» - PullRequest
2 голосов
/ 03 июня 2019

Я новичок в Spring Boot / JPA.Я пытаюсь выполнить операцию CRUD для модели такси.

Я получаю следующую ошибку:

com.microsoft.sqlserver.jdbc.SQLServerException: Неверное имя столбца 'taxi_id'

Любая помощь будет принята с благодарностью.

Это мой код хранилища:

            package com.example.SpringBoot.Model.Repository;

            import org.springframework.data.repository.CrudRepository;
            import com.example.SpringBoot.Model.Taxi;

            public interface DAO extends CrudRepository<Taxi, Integer>{
            }

Контроллер

            package com.example.SpringBoot.Controller;

            import java.util.List;
            import org.springframework.beans.factory.annotation.Autowired;
            import org.springframework.web.bind.annotation.DeleteMapping;
            import org.springframework.web.bind.annotation.GetMapping;
            import org.springframework.web.bind.annotation.PostMapping;
            import org.springframework.web.bind.annotation.PutMapping;
            import org.springframework.web.bind.annotation.RequestMapping;
            import org.springframework.web.bind.annotation.RequestParam;
            import org.springframework.web.bind.annotation.RestController;
            import com.example.SpringBoot.Model.Taxi;
            import com.example.SpringBoot.Model.Repository.DAO;


            @RestController
            public class TaxiController {

                @Autowired
                public DAO repo;

                @PutMapping(path= "/Taxi" , produces = {"application/json"})
                public Taxi insertTaxi(Taxi taxi) {
                    repo.save(taxi);
                    return taxi;
                }

                @DeleteMapping(path ="/Taxi/{TaxiId}")
                public void deleteTaxi(@RequestParam int TaxiId) {

                    repo.deleteById(TaxiId);
                }

                @GetMapping(path ="/Taxi")
                public List<Taxi> displayTaxi() {
                    return (List<Taxi>) repo.findAll();
                }
            }

Класс модели

            package com.example.SpringBoot.Model;

            import java.math.BigDecimal;
            import javax.persistence.Entity;
            import javax.persistence.GeneratedValue;
            import javax.persistence.GenerationType;
            import javax.persistence.Id;

            @Entity
            public class Taxi {

                @Id
                @GeneratedValue(strategy = GenerationType.AUTO)
                private int TaxiId;
                private String TaxiType;


                public int getTaxiId() {
                    return TaxiId;
                }


                public void setTaxiId(int taxiId) {
                    TaxiId = taxiId;
                }

                public String getTaxiType() {
                    return TaxiType;
                }

                public void setTaxiType(String taxiType) {
                    TaxiType = taxiType;
                }
            }

Код SQL-сервера

            CREATE TABLE [dbo].[Taxi](
            [Taxiid] [int] IDENTITY(1,1) NOT NULL,
            [TaxiType] [varchar](1) NOT NULL,

            PRIMARY KEY CLUSTERED 
            (
            [TaxiId] ASC
            )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
            ) ON [PRIMARY]

Трассировка стека:

                  .   ____          _            __ _ _
                 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
                ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
                 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
                  '  |____| .__|_| |_|_| |_\__, | / / / /
                 =========|_|==============|___/=/_/_/_/
                 :: Spring Boot ::        (v2.1.4.RELEASE)

                2019-06-03 15:37:24.554  INFO 7808 --- [           main] c.e.SpringBoot.TaxiBookingApplication    : Starting TaxiBookingApplication on IMCHLT080 with PID 7808 (D:\workspace\TaxiBooking\target\classes started by vignesh_nithin in D:\workspace\TaxiBooking
                .............
                2019-06-03 15:37:34.446  INFO 7808 --- [nio-8081-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
                2019-06-03 15:37:34.456  INFO 7808 --- [nio-8081-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 10 ms
                2019-06-03 15:37:34.530  INFO 7808 --- [nio-8081-exec-1] o.h.h.i.QueryTranslatorFactoryInitiator  : HHH000397: Using ASTQueryTranslatorFactory
                2019-06-03 15:37:34.645  WARN 7808 --- [nio-8081-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 207, SQLState: S0001
                2019-06-03 15:37:34.645 ERROR 7808 --- [nio-8081-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper   : Invalid column name 'taxi_id'.
                2019-06-03 15:37:34.668 ERROR 7808 --- [nio-8081-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet] with root cause

                com.microsoft.sqlserver.jdbc.SQLServerException: Invalid column name 'taxi_id'.
                    at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:259) ~[mssql-jdbc-6.4.0.jre8.jar:na]
                    at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1547) ~[mssql-jdbc-6.4.0.jre8.jar:na]
                    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:548) ~[mssql-jdbc-6.4.0.jre8.jar:na]
                    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:479) ~[mssql-jdbc-6.4.0.jre8.jar:na]

Я ожидаю, что данные таблицы Такси будут отображаться / вставляться / удаляться в зависимости от URL-адреса.

1 Ответ

3 голосов
/ 03 июня 2019

Ваша конфигурация постоянства по умолчанию, кажется, переводит регистр верблюдов, разделяя его подчеркиванием. Так что если у вас есть:

   @Id
   @GeneratedValue(strategy = GenerationType.AUTO)
   private int TaxiId;

он попытается использовать: 'taxi_id';

Как на дб у вас есть:

        CREATE TABLE [dbo].[Taxi](
        [Taxiid] [int] IDENTITY(1,1) NOT NULL,

Вам следует либо изменить имя поля на «Taxiid», либо явно указать имя столбца:

 @Id
 @GeneratedValue(strategy = GenerationType.AUTO)
 @Column(name = "Taxiid")
 private int TaxiId;

Вы также можете попытаться изменить используемую по умолчанию стратегию именования, изменив соответственно следующие свойства:

spring.jpa.hibernate.naming.implicit-strategy
spring.jpa.hibernate.naming.physical-strategy
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...