【问题标题】:How to load data from Database and instance the entity (Hibernate & Spring)如何从数据库加载数据并实例化实体(Hibernate 和 Spring)
【发布时间】:2019-02-21 10:43:24
【问题描述】:

我想通过 id 从保存对象的数据库中获取对象 ResponsableEntity。我第一次使用 Spring-boot 和 hibernate,其他主题的懒散在我的项目中不起作用

这是我的代码:

责任实体:

@Entity
@Table(name = "responsable")
public class ResponsableEntity {

    /**
     * Id of the responsable
     */
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    /**
     * First name of the responsable
     */
    @Column(nullable=false)
    private String firstName;

    /**
     * Lst name of the responsable
     */
    @Column(nullable=false)
    private String lastName;

    /**
     * Last latitude of the  responsable position
     */
    private Double latitude;

    /**
     * Last longitude of the  responsable position
     */
    private Double longitude;

    /**
     * All getters and setters [...]
     */
}

ResponsableDBRepository:

@Repository
public interface ResponsableDBRepository extends CrudRepository<ResponsableEntity, Long> {
}

责任控制器(REST):

@RestController
@RequestMapping("/responsable")
public class ResponsableController {

    /**
     * CRUD Repository atribut needed for the methods below
     */

    private final ResponsableDBRepository responsableDBRepository;
    private final ResponsableStatDBRepository responsableStatDBRepository;

    /**
     * Constructor
     *
     * @param responsableDBRepository CRUD repository for ResponsableEntity
     * @param responsableStatDBRepository CRUD repository for ResponsableStatEntity
     */
    @Autowired
    public ResponsableController(ResponsableDBRepository responsableDBRepository, ResponsableStatDBRepository responsableStatDBRepository){
        this.responsableDBRepository = responsableDBRepository;
        this.responsableStatDBRepository = responsableStatDBRepository;
    }

    @GetMapping(path = "/get")
    public @ResponseBody String getAllResponsable(){

        //get object with id given

        return "Returned";
    }
}

我希望当我们调用此请求时,从数据库加载实体并使用保存在数据库中的信息创建一个对象 ResponsableEntity。我已经尝试了我在其他主题上找到的大部分答案,但大多数时候我的 IDE 告诉我他找不到所需的类,而且它似乎是来自 Hibernate 和 Spring 的“默认”类

提前感谢您的回答!

【问题讨论】:

  • IDE 找不到哪个类?
  • 您的方法名称getAllResponsable() 表明您要查找所有 实体,而不仅仅是具有特定ID 的实体。您的存储库有很多查找实体的方法。请参阅documentation of Spring Data JPA 了解如何使用它们。
  • 嗨 Flo_H99,您可能在您的 ResponsableStatDBRepository 中错过了 spring annotation@Autowired
  • 坦克Yogendra :)

标签: java spring hibernate rest


【解决方案1】:

使用这个:-

ResponsableEntity responsableEntity = responsableDBRepository.findById(id);

【讨论】:

  • 我已经尝试过了,但是女巫类型的 id 变量必须是?我尝试了 long 和 int 但总是出现这个错误:“CrudRepository 中的 findById(java.lang.Long) 无法应用于 ()”
猜你喜欢
  • 2017-04-05
  • 2016-02-24
  • 2014-07-14
  • 2021-09-05
  • 1970-01-01
  • 2016-08-04
  • 2012-06-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多