SQLGrammerException: не удалось подготовить оператор, ошибка белой метки - PullRequest
0 голосов
/ 04 мая 2020

Я пытаюсь создать веб-приложение с весенней загрузкой, которое позволило бы мне добавлять и удалять пользователей, каждый из которых имеет определенные атрибуты c. Я застрял в этом. Пожалуйста, помогите.

Я получаю следующую ошибку при запуске файла jar с помощью команды java -jar:

There was an unexpected error (type=Internal Server Error, status=500).
could not prepare statement; SQL [select userentity0_.id as id1_0_, userentity0_.c_burnt as c_burnt2_0_, userentity0_.h_rate as h_rate3_0_, userentity0_.name as name4_0_, userentity0_.workout as workout5_0_ from tbl_users userentity0_]; nested exception is org.hibernate.exception.SQLGrammarException: could not prepare statement

Содержимое:

схема. sql:

DROP TABLE IF EXISTS TBL_USERS;

CREATE TABLE TBL_USERS (
  id INT AUTO_INCREMENT  PRIMARY KEY,
  name VARCHAR(250) NOT NULL,
  cBurnt VARCHAR(250) NOT NULL,
  hRate VARCHAR(250) NOT NULL,
  workout VARCHAR(250) NOT NULL
);

data. sql:

INSERT INTO 
    TBL_USERS (name, cBurnt, hRate, workout) 
VALUES
    ('Lokesh', '100', '60', '25'),
    ('Lokesh', '200', '72', '35'),
    ('Tim', '170', '84', '30');

userentity. java:

package com.richi.demo.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="TBL_USERS")
public class UserEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

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

    @Column(name="cBurnt")
    private String cBurnt;

    @Column(name="hRate")
    private String hRate;

    @Column(name="workout")
    private String workout;



    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCBurnt() {
        return cBurnt;
    }

    public void setCBurnt(String cBurnt) {
        this.cBurnt = cBurnt;
    }


    public String getHRate() {
        return hRate;
    }

    public void setHRate(String hRate) {
        this.hRate = hRate;
    }


    public String getWorkout() {
        return workout;
    }

    public void setWorkout(String workout) {
        this.workout = workout;
    }



    @Override
    public String toString() {
        return "UserEntity [id=" + id + ", name=" + name + 
                ", cBurnt=" + cBurnt + ", hRate=" + hRate+ ", workout="+workout   + "]";



    }
}

UserService. java:

package com.richi.demo.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.richi.demo.exception.RecordNotFoundException;
import com.richi.demo.model.UserEntity;
import com.richi.demo.repository.UserRepository;

@Service
public class UserService {

    @Autowired
    UserRepository repository;

    public List<UserEntity> getAllUsers()
    {
        List<UserEntity> result = (List<UserEntity>) repository.findAll();

        if(result.size() > 0) {
            return result;
        } else {
            return new ArrayList<UserEntity>();
        }
    }

    public UserEntity getUserById(Long id) throws RecordNotFoundException 
    {
        Optional<UserEntity> user = repository.findById(id);

        if(user.isPresent()) {
            return user.get();
        } else {
            throw new RecordNotFoundException("No user record exist for given id");
        }
    }

    public UserEntity createOrUpdateUser(UserEntity entity) 
    {
        if(entity.getId()  == null) 
        {
            entity = repository.save(entity);

            return entity;
        } 
        else 
        {
            Optional<UserEntity> user = repository.findById(entity.getId());

            if(user.isPresent()) 
            {
                UserEntity newEntity = user.get();
                newEntity.setName(entity.getName());
                newEntity.setCBurnt(entity.getCBurnt());
                newEntity.setHRate(entity.getHRate());
                newEntity.setWorkout(entity.getWorkout());

                newEntity = repository.save(newEntity);

                return newEntity;
            } else {
                entity = repository.save(entity);

                return entity;
            }
        }
    } 

    public void deleteUserById(Long id) throws RecordNotFoundException 
    {
        Optional<UserEntity> user = repository.findById(id);

        if(user.isPresent()) 
        {
            repository.deleteById(id);
        } else {

            throw new RecordNotFoundException("No user record exist for given id");
        }
    } 
}

и UserMvcController. java:

package com.richi.demo.web;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.richi.demo.exception.RecordNotFoundException;
import com.richi.demo.model.UserEntity;
import com.richi.demo.service.UserService;

@Controller
@RequestMapping("/")
public class UserMvcController 
{
    @Autowired
    UserService service;

    @RequestMapping
    public String getAllUsers(Model model) 
    {
        List<UserEntity> list = service.getAllUsers();

        model.addAttribute("users", list);
        return "list-users";
    }

    @RequestMapping(path = {"/edit", "/edit/{id}"})
    public String editUserById(Model model, @PathVariable("id") Optional<Long> id) 
                            throws RecordNotFoundException 
    {
        if (id.isPresent()) {
            UserEntity entity = service.getUserById(id.get());
            model.addAttribute("user", entity);
        } else {
            model.addAttribute("user", new UserEntity());
        }
        return "add-edit-user";
    }

    @RequestMapping(path = "/delete/{id}")
    public String deleteUserById(Model model, @PathVariable("id") Long id) 
                            throws RecordNotFoundException 
    {
        service.deleteUserById(id);
        return "redirect:/";
    }

    @RequestMapping(path = "/createUser", method = RequestMethod.POST)
    public String createOrUpdateUser(UserEntity user) 
    {
        service.createOrUpdateUser(user);
        return "redirect:/";
    }
}

Может кто-нибудь сказать, пожалуйста, что не так ??? Я пытался отладить это в течение последних 3 часов :(.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...