简体   繁体   中英

How to load data from Database and instance the entity (Hibernate & Spring)

I would like to get objects ResponsableEntity by id from the Database where they are saved. I use Spring-boot and hibernate for the first time and the slouches on other topics don't work in my project

Here are my code :

ResponsableEntity :

@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> {
}

ResponsableController (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";
    }
}

I'd like that when we call this request, the entity is load from the database and an object ResponsableEntity is created with the infos saved in the database. I already tried most of the answer I found on other topics but most of the time my IDE told me he can't find the class required and it seems to be "default" classes from Hibernate and Spring

Thank you in advance for your answer !

用这个:-

ResponsableEntity responsableEntity = responsableDBRepository.findById(id);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM