【问题标题】:findByAll(), findBy{columnName} is not working in Spring data jpafindByAll(), findBy{columnName} 在 Spring 数据 jpa 中不起作用
【发布时间】:2020-07-30 18:39:55
【问题描述】:

我是 Spring Boot 和 Spring Data JPA 的初学者。我正在尝试从表中获取所有数据,并且还想通过用户名获取数据,所以我在我的存储库中使用 findAll()findByUsername(String username) 方法。我在我的存储库界面中扩展了 JpaRepository。但无法获取数据。 findAll() 返回空对象 findByUsername 返回空对象。表中有一条记录。还有一件事,repository.save(object) 方法工作正常。仅在 find 方法中面临问题。

我的存储库界面。

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.SpringBoot.model.User;

@Repository
public interface UserRepository extends JpaRepository<User, Long> {

    User findByUsername(String username);
}

我的服务等级。

@Service
public class UserServiceImp {

    UserRepository userRepository;

    public List<User> getAllUsers() throws Exception {
        return (List<User>) userRepository.findAll();
    }

    public User getUserById(String username) throws Exception {
        System.out.println("in service imp class ***************************");
        return userRepository.findByUsername(username);
    }

    public void addUsers(User user) throws Exception {
        userRepository.save(user);

    }
}

我的实体类。

@Entity
public class User implements Serializable {

    private static final long serialVersionUID = 1L;

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

    private String username;
    private String name;
    private int userCode;

    public Long getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getName() {
        return name;
    }

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

    public int getUserCode() {
        return userCode;
    }

    public void setUserCode(int userCode) {
        this.userCode = userCode;
    }
}

我的控制器

package com.SpringBoot.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
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.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.SpringBoot.model.User;
import com.SpringBoot.service.Userservice;

@RestController
public class UserController {

    @Autowired
    UserServiceImp userservice;

    @PostMapping("/user/add")
    public void addUsers(@RequestBody User user) {
        try {
            userservice.addUsers(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @GetMapping("/user/{id}")
    public User getUserById(@PathVariable("id") String username) {
        User user = null;
        try {
            System.out.println("***************  " + username);
            user = userservice.getUserById(username);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return user;
    }


    @GetMapping(value = "/users")
    public List<User> getAllUser() {
        List<User> user = new ArrayList<User>();
        System.out.println("***************  ");
        try {
            user = userservice.getAllUsers();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return user;
    }
}

我的 pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.test.junit</groupId>
    <artifactId>SpringBoot</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.1.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.4</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

【问题讨论】:

  • 当您在查询数据库时从未得到任何结果时,您怎么知道保存方法工作正常?另外:您的交易边界在哪里?
  • 我已经使用 save() 在表中成功插入了一条记录。

标签: java spring-boot spring-data-jpa spring-data


【解决方案1】:

不确定您使用的是哪个数据库,但例如在 Postgres 中,术语“用户”是保留关键字。只有提供带引号的名称才能与休眠一起使用:

@Table(name="\"user\"")

注意大小写。

你可以在https://bootify.io创建一个小项目,它会给你一个运行配置。

【讨论】:

    【解决方案2】:

    您需要使用@Autowired 或使用构造函数注入在服务类中注入存储库。 Spring推荐构造函数注入

    @Service
    public class UserServiceImp {
    
    private final UserRepository userRepository;
    
    public UserServiceImp(final UserRepository userRepository){
        this.userRepository=userRepository;
    }
    
    
    
    public List<User> getAllUsers() throws Exception {
        return (List<User>) userRepository.findAll();
    }
    
    public User getUserById(String username) throws Exception {
        // FiXME
        System.out.println("in service imp class ***************************");
        return userRepository.findByUsername(username);
    }
    
    public void addUsers(User user) throws Exception {
        userRepository.save(user);
    
     }
    }
    

    【讨论】:

      【解决方案3】:

      尝试通过将表列名称链接到每个实体类成员来修改您的实体类。例如。

      @Entity
      @Table(name="USER")
      public class User implements Serializable {
      
          private static final long serialVersionUID = 1L;
      
          @Id
          @GeneratedValue(strategy = GenerationType.AUTO)
          @Column(name="ID", unique=true, nullable=false, precision=20)
          private Long id;
      
          @Column(name="USERNAME", length=100)
          private String username;
      
          @Column(name="NAME", length=100)
          private String name;
      
          @Column(name="USER_CODE", precision=20)
          private int userCode;
      }
      

      通过 如果上面的代码不起作用,请尝试通过创建 JPA 项目并从表中导入实体来生成实体类

      【讨论】:

        猜你喜欢
        • 2018-07-15
        • 1970-01-01
        • 2018-02-09
        • 1970-01-01
        • 2021-11-28
        • 2022-01-09
        • 2021-09-11
        • 2015-09-29
        • 2017-09-11
        相关资源
        最近更新 更多