Spring JPA find by method is getting SQL statement error

3okqufwl  于 2023-10-20  发布在  Spring
关注(0)|答案(1)|浏览(95)

我正在创建一个餐饮评论的API。我正在使用Spring MVC方法,并试图使用URL为http://localhost:8080/user/add的post方法将用户添加到我的数据库中。我能够连接到我的spring应用程序,我看到一切都按预期工作,直到我的应用程序尝试运行我在repo中创建的findByUsername方法。这是我的模型课

package com.dining.model;

import org.springframework.stereotype.Component;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Component
@NoArgsConstructor
@AllArgsConstructor
@Data
@Entity(name = "User")
@Table(name = "User")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String username;
    private String city;
    private String state;
    private String zip;
    private boolean peanutAll;
    private boolean eggAll;
    private boolean dairyAll;
    

    
    
}

控制器

package com.dining.controller;

import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.dining.exceptions.UserAlreadyExistsException;
import com.dining.model.User;
import com.dining.service.UserService;

import jakarta.validation.Valid;

@RestController

@RequestMapping(path="/user")
public class UserController {
    @Autowired UserService userv;
    @Autowired User returnUser;
    @PostMapping("/add")
    public ResponseEntity<User> addUser(@Valid @RequestBody User user){
        System.out.print(user.getUsername());
    Optional<User> tempUser =   userv.getUser(user.getUsername());
    if(tempUser.isEmpty()) {
        returnUser = userv.addUser(user);
        return ResponseEntity.ok(returnUser);
    }
    else {
        throw new UserAlreadyExistsException(String.format("User %s already exists", user.getUsername()));
    }

    }
}

服务层

package com.dining.service;

import java.util.Optional;
import java.util.logging.Logger;

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

import com.dining.data.UserRepo;
import com.dining.exceptions.ChangeUsernameException;
import com.dining.exceptions.UserNotFoundException;
import com.dining.model.User;

@Service
public class UserService {

    @Autowired UserRepo userRepo;
    @Autowired User tempUser;
    
    
    public User addUser(User user) {
        try {
            if(userRepo.findByUsername(user.getUsername()) != null) {
                throw new SecurityException();
            }
            else {
                tempUser = userRepo.save(user);
                //future implementation is to add security (password)
                return tempUser;
                        
            }
        }
        
        catch(SecurityException ex) {
            ex.printStackTrace();
            System.out.printf("Username %s", user.getUsername())
            
        }
        catch(Exception ex) {
            ex.printStackTrace();
        }
        
        
    }
    
    public Optional<User> getUser(String username) {
        
        Optional <User> tempUser = userRepo.findByUsername(username);
        if(tempUser.isEmpty()){
            throw new UserNotFoundException(String.format("Unable to find user: %s", username));
            
        }
        else {
            return tempUser;
        }
    
    
    }

}
package com.dining.data;

import java.util.Optional;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import com.dining.model.User;
@Repository
public interface UserRepo extends JpaRepository<User, Integer>{
    

    Optional<User> findByUsername(String username);
}

我已经尝试发送这个JSON对象作为我的请求的主体。我相信SQL错误来自用户名值未被读取。显示username =?sql语句中

{
    "id": 1,
    "username":"Jb",
    "city": "toledo",
    "state": "NC",
    "zip": "43706",
    "peanutAll":"false",
    "eggAll":"false",
    "dairyAll":"false"
}

我注意到,如果我在对象中拼错了用户名键,它不会抛出错误。它仍然尝试运行sql语句,但显示username = null。下面是我得到的错误堆栈跟踪
org. springframework. dao. InvalidDataAccessResourceUsageException:无法准备语句[SQL语句中出现语法错误"select u1_0.id,u1_0.city,u1_0.dairy_all,u1_0.egg_all,u1_0.peanut_all,u1_0.state,u1_0.username,u1_0.zip from [*] user u1_0 where u1_0.username =?";应为"标识符"; SQL语句:\nselect u1_0.id,u1_0.city,u1_0.dairy_all,u1_0.egg_all,u1_0.peanut_all,u1_0.state,u1_0.username,u1_0.zip from user u1_0 where u1_0.username =?[42001 - 214]][select u1_0.id,u1_0.city,u1_0.dairy_all,u1_0.egg_all,u1_0.peanut_all,u1_0.state,u1_0.username,u1_0.zip from user u1_0 where u1_0.username =?]; SQL [select u1_0.id,u1_0.city,u1_0.dairy_all,u1_0.egg_all,u1_0.peanut_all,u1_0.state,u1_0.username,u1_0.zip from user u1_0 where u1_0.username =?]\r\n\tat组织。SpringFramework orm.卖主。休眠Jpa方言。convertHibernateAccessException(HibernateJpaDialect.java:256)\r\n\tat org. SpringFramework orm.卖主。休眠Jpa方言。translateExceptionIfPossible(HibernateJpaDialect.java:229)\r\n\tat org. SpringFramework orm. AbstractEntityManagerFactoryBean。translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:550)\r\n\tat org. SpringFramework dao.支持。ChainedPersistenceExceptionTranslator。translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61)\r\n\tat org. SpringFramework dao.支持。DataAccessUtils。translateIfNecessary(DataAccessUtils.java:242)\r\n\tat org. SpringFramework dao.支持。PersistenceExceptionTranslationInterceptor。invoke(PersistenceExceptionTranslationInterceptor.java:152)\r\n\tat org. SpringFramework aop。框架。ReflectiveMethod调用。proceed(ReflectiveMethodInvocation.java:184)\r\n\tat org. SpringFramework数据。jpa仓库。支持。CrudMethodMetadataPostProcessor $CrudMethodMetadataPopulatingMethodInterceptor。invoke(CrudMethodMetadataPostProcessor.java:135)\r\n\tat org. SpringFramework aop。框架。ReflectiveMethod调用。proceed(ReflectiveMethodInvocation.java:184)\r\n\tat org. SpringFramework aop。拦截器ExposeInvocationInterceptor。invoke(ExposeInvocationInterceptor.java:97)\r\n\tat org. SpringFramework aop。框架。ReflectiveMethod调用。proceed(ReflectiveMethodInvocation.java:184)\r\n\tat org. SpringFramework aop。框架。JdkDynamicAopProxy。invoke(JdkDynamicAopProxy.java:244)\r\n\tat jdk.proxy5/jdk.proxy5.$Proxy120.findByUsername(未知源)\r\n\tat com.用餐服务。UserService. getUser(UserService.java:48)

xoefb8l8

xoefb8l81#

是使用H2的数据库还是任何将USER作为保留关键字的数据库?从错误堆栈跟踪来看,这就是我所怀疑的。尝试将您的表重命名为自定义名称,如 UserSummary,并查看这是否仍然可重现。或者你可以在www.example.com中使用这个application.properties:

spring.jpa.properties.hibernate.globally_quoted_identifiers=true

更多关于here

相关问题