java.sql.sqlexception:列' serialnumber'未找到。 (春季靴)

发布于 2025-01-18 10:50:27 字数 3664 浏览 0 评论 0原文

我正在用Spring Boot编写待办事项列表Web应用程序。 我有两个实体: 用户(字段:userId(id),用户名,密码 项目(字段:SerialNumber(ID),任务,用户ID。 我想让每个用户只看到他的任务。因此,我尝试从“任务”表中拉出所有任务。当我尝试通过自定义查询检索信息时(我认为)Hibernate无法读取表。但是,当我从存储库接口中使用诸如Findall()之类的内置方法时,它的工作原理。

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

@Entity
public class Item {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer serialnumber;
    private int userid;
    private String task;

    public Item() {

    }

    public Item(int userid, String task) {
        this.userid = userid;
        this.task = task;
    }

    public Integer getSerialnumber() {
        return serialnumber;
    }

    public void setSerialnumber(Integer serialnumber) {
        this.serialnumber = serialnumber;
    }

    public int getUserid() {
        return userid;
    }

    public void setUserid(int userid) {
        this.userid = userid;
    }

    public String getTask() {
        return task;
    }

    public void setTask(String task) {
        this.task = task;
    }

    @Override
    public String toString() {
        return "Item{" +
                "serialnumber=" + serialnumber +
                ", userid=" + userid +
                ", task='" + task + '\'' +
                '}';
    }
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class MainController {


    @Autowired
    private ItemRepository itemRepository;

.....

@PostMapping("/addItem")
    public String addItem(@RequestParam String task,
                          @CookieValue(name = "id") String id,
                          Model model) {

        Item item = new Item(Integer.valueOf(id), task);
        itemRepository.save(item);
        print(item.toString());
        model.addAttribute("items", itemRepository.findItemsByUserId(Integer.valueOf(id)));
        return "list";
    } 
......
}
import org.springframework.data.repository.CrudRepository;

import java.util.List;

public interface ItemRepository extends CrudRepository<Item, Integer> {

    @Query(value = "SELECT task FROM item WHERE userid = ?1", nativeQuery = true)
    List<Item> findItemsByUserId(Integer userid);

}
Hibernate: SELECT task FROM item WHERE userid = ?
2022-04-02 23:23:45.733  WARN 36504 --- [nio-8080-exec-6] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 0, SQLState: S0022
2022-04-02 23:23:45.733 ERROR 36504 --- [nio-8080-exec-6] o.h.engine.jdbc.spi.SqlExceptionHelper   : Column 'serialnumber' not found.
2022-04-02 23:23:45.743 ERROR 36504 --- [nio-8080-exec-6] 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 execute query; SQL [SELECT task FROM item WHERE userid = ?]; nested exception is org.hibernate.exception.SQLGrammarException: could not execute query] with root cause

java.sql.SQLException: Column 'serialnumber' not found.
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129) ~[mysql-connector-java-8.0.28.jar:8.0.28]

I am writing to-do list web app with spring boot.
I Have 2 entities:
User (fields: userid (ID), username, password
Item (fields: serialnumber (ID), task, userid.
I want to allow each user to see only his tasks. So I try to pull all the tasks from "task" table. When I try to retrieve information by a custom query, (I think) hibernate fails to read the table. But when I use a built-in method like findAll() from the Repository interface it's works.

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

@Entity
public class Item {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer serialnumber;
    private int userid;
    private String task;

    public Item() {

    }

    public Item(int userid, String task) {
        this.userid = userid;
        this.task = task;
    }

    public Integer getSerialnumber() {
        return serialnumber;
    }

    public void setSerialnumber(Integer serialnumber) {
        this.serialnumber = serialnumber;
    }

    public int getUserid() {
        return userid;
    }

    public void setUserid(int userid) {
        this.userid = userid;
    }

    public String getTask() {
        return task;
    }

    public void setTask(String task) {
        this.task = task;
    }

    @Override
    public String toString() {
        return "Item{" +
                "serialnumber=" + serialnumber +
                ", userid=" + userid +
                ", task='" + task + '\'' +
                '}';
    }
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class MainController {


    @Autowired
    private ItemRepository itemRepository;

.....

@PostMapping("/addItem")
    public String addItem(@RequestParam String task,
                          @CookieValue(name = "id") String id,
                          Model model) {

        Item item = new Item(Integer.valueOf(id), task);
        itemRepository.save(item);
        print(item.toString());
        model.addAttribute("items", itemRepository.findItemsByUserId(Integer.valueOf(id)));
        return "list";
    } 
......
}
import org.springframework.data.repository.CrudRepository;

import java.util.List;

public interface ItemRepository extends CrudRepository<Item, Integer> {

    @Query(value = "SELECT task FROM item WHERE userid = ?1", nativeQuery = true)
    List<Item> findItemsByUserId(Integer userid);

}
Hibernate: SELECT task FROM item WHERE userid = ?
2022-04-02 23:23:45.733  WARN 36504 --- [nio-8080-exec-6] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 0, SQLState: S0022
2022-04-02 23:23:45.733 ERROR 36504 --- [nio-8080-exec-6] o.h.engine.jdbc.spi.SqlExceptionHelper   : Column 'serialnumber' not found.
2022-04-02 23:23:45.743 ERROR 36504 --- [nio-8080-exec-6] 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 execute query; SQL [SELECT task FROM item WHERE userid = ?]; nested exception is org.hibernate.exception.SQLGrammarException: could not execute query] with root cause

java.sql.SQLException: Column 'serialnumber' not found.
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129) ~[mysql-connector-java-8.0.28.jar:8.0.28]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

天涯离梦残月幽梦 2025-01-25 10:50:27

问题可能是您的查询在选择子句中指定列task,但是您期望list&lt; item&gt;作为findItemsbyuserId中的返回类型方法。

如果您希望返回整个item,则应将查询更改为“从userId =?1”的项目中选择 * *,以便选择所有列。

但是,如果您想要的是字段task,则必须更改方法返回类型,因为您需要投影(特定列选择)。
这可以通过定义一个界面来完成:

public interface TaskDto {
    String getTask();
}

然后您必须选择

@Query(value = "SELECT task FROM item WHERE userid = ?1", nativeQuery = true)
List<TaskDto> findItemsByUserId(Integer userid);

@Query(value = "SELECT * FROM item WHERE userid = ?1", nativeQuery = true)
List<Item> findItemsByUserId(Integer userid);

The problem could probably be that your query specifies the column task in the select clause, but you're expecting a List<Item> as return type in the findItemsByUserId method.

If you want the entire Item to be returned, then you should change your query to "SELECT * FROM item WHERE userid = ?1" in order to select all columns.

But, if what you want is the field task only, then you must change the method return type because you want a projection (specific columns selection).
That could be done by defining an interface like:

public interface TaskDto {
    String getTask();
}

Then you have to choose between:

@Query(value = "SELECT task FROM item WHERE userid = ?1", nativeQuery = true)
List<TaskDto> findItemsByUserId(Integer userid);

and

@Query(value = "SELECT * FROM item WHERE userid = ?1", nativeQuery = true)
List<Item> findItemsByUserId(Integer userid);
咆哮 2025-01-25 10:50:27
@Query(value = "SELECT task FROM item WHERE userid = ?1", nativeQuery = true)
List<Item> findItemsByUserId(Integer userid);

显然,您的查询正在返回字符串值列表,并且您正在尝试将它们转换为 Item 实体的列表。

如果您想以项目列表的形式获取结果,请使用

@Query(value = "SELECT * FROM item WHERE userid = ?1", nativeQuery = true)
List<Item> findItemsByUserId(Integer userid);

,或者如果您只需要任务的字符串列表,请使用

@Query(value = "SELECT task FROM item WHERE userid = ?1", nativeQuery = true)
List<String> findItemsByUserId(Integer userid);

相应的更改调用方方法。
根据您的错误“未找到序列号”,而 JPA/Hibernate 使用反射 API 将表中的各个列映射到实体中的相应字段。
由于您专门获取“任务”,因此所有其他列都丢失了。因此“未找到序列号”。

@Query(value = "SELECT task FROM item WHERE userid = ?1", nativeQuery = true)
List<Item> findItemsByUserId(Integer userid);

Clearly your query is returning a List of String values and you are trying to cast them to List of your Item entity.

If you want to fetch your result as List of item, use

@Query(value = "SELECT * FROM item WHERE userid = ?1", nativeQuery = true)
List<Item> findItemsByUserId(Integer userid);

or if you want just the String list of tasks, use

@Query(value = "SELECT task FROM item WHERE userid = ?1", nativeQuery = true)
List<String> findItemsByUserId(Integer userid);

Change the caller methods accordingly.
As per your error "serialnumber not found", while JPA/Hibernate use reflection API for mapping individual columns from table to their appropriate fields in entity.
Since you are specifically fetching "task", all the other columns are missing. Hence "serialnumber not found".

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文