与 Spring Data JPA 的一对多关系,@Entity 类型无法识别

问题描述 投票:0回答:1

我正在尝试在 Spring Boot 应用程序中创建单向一对多关系。我有用户和设备。一个用户可以拥有多台设备。 我正在使用微服务,因此我有一个用于用户的模块和一个用于设备的模块。 这是我的用户类

package com.demo.user.entity;

import com.demo.device.entity.Device;
import jakarta.persistence.*;

import java.util.List;

@Entity
@Table(name = "user")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String name;
    private String role;
    @OneToMany(cascade= {CascadeType.ALL})
    @JoinColumn(name="ud_fk",referencedColumnName = "id")
    private List<Device> devices;

    public List<Device> getDevices() {
        return devices;
    }

    public void setDevices(List<Device> devices) {
        this.devices = devices;
    }

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getRole() {
        return role;
    }

    public void setRole(String role) {
        this.role = role;
    }

}

这是我的设备类

package com.demo.device.entity;

import jakarta.persistence.*;

@Entity
@Table(name = "device")
public class Device {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String description;
    private String address;
    private int consumption;

    public int getId() {
        return id;
    }

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

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public int getConsumption() {
        return consumption;
    }

    public void setConsumption(int consumption) {
        this.consumption = consumption;
    }
}

这是我尝试创建一对多关系时遇到的错误。

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Association 'com.demo.user.entity.User.devices' targets the type 'com.demo.device.entity.Device' which is not an '@Entity' type

我不明白为什么设备不被识别为@Entity,因为我在那里有那个注释...... 请帮忙!

spring jpa relationship one-to-many boot
1个回答
0
投票

代码看起来不错。也许 Spring 无法找到您的实体。尝试在主文件或某些配置文件中设置

EntityScan
,看看问题是否仍然存在:

@Configuration
@EntityScan("com.baeldung.demopackage")
public class EntityScanDemo {
    // ...
}
© www.soinside.com 2019 - 2024. All rights reserved.