【问题标题】:How to Get Specific Object Using SelectById(object_id) in SpringBoot-MyBatis-MySQL?如何在 SpringBoot-MyBatis-MySQL 中使用 SelectById(object_id) 获取特定对象?
【发布时间】:2019-10-07 13:58:36
【问题描述】:

我设法通过在 SpringBoot-MyBatis 后端创建一个 SELECT 语句来“获取所有对象”,例如:

AppRestController.java

//get full list of actors 
@GetMapping("/actors")
public List<Actor> selectAllActors(){
        return actorMapper.selectAllActors();
}

当您在浏览器中键入“localhost:9090/actors”时,它将返回我的 MySQL 数据库中的所有参与者对象。那挺好的。现在我想把它的复杂性提高一个档次。

我想通过它的 actor_id 获取单个对象,例如:

//get specific actor by actor_id. this is where im stuck
@GetMapping("/actors/id")
public Actor selectActorById(int id){
     return actorMapper.selectActorById(id);
}

注意我的 @GetMapping。我想要做的是当我输入类似 "localhost:9090/actors/1" 在浏览器中,它将从数据库中返回 id = 1 的 actor 对象,依此类推。

这里是相关文件。

ActorMapper.xml

<mapper namespace="com.helios.mybatissakila.mappers.ActorMapper">

    <resultMap id="ActorResultMap" type="Actor">
        <id column="actor_id" property="actor_id" jdbcType="INTEGER"/>
        <result column="first_name" property="first_name" />
        <result column="last_name" property="last_name" />
        <result column="last_update" property="last_update" />
    </resultMap>

<select id="selectAllActors" resultMap="ActorResultMap">
        select * from actor
</select>

<select id="selectActorById" resultMap="ActorResultMap">
        select * from actor where actor_id = #{actor_id}
</select>

</mapper> 

ActorMapper.java

@Mapper
public interface ActorMapper {
    //this is now working
    List <Actor> selectAllActors();
    //this is where im stuck
    Actor selectActorById(int id);
}

感谢您的帮助。 更新

所以我确实改变了

@GetMapping("/actors/id")
public Actor selectActorById(int id){
     return actorMapper.selectActorById(id);
}

@GetMapping("/actors/{id}")
public Actor selectActorById(Integer id){
     return actorMapper.selectActorById(id);
}

显然,没有错误,但我得到一个空白屏幕。为什么?我的 MySQL 数据库中有一个数据,其 actor_id 等于 1。

【问题讨论】:

  • 请不要在此处使用 [已解决的] 标题黑客 - 我们不会在 Stack Overflow 上使用它们。如果您有答题材料,则需要将其放入答案中。

标签: mysql spring spring-boot mybatis ibatis


【解决方案1】:

如下更改您的 get 映射:

@GetMapping("/actors/{id}")
public Actor selectActorById(@PathVariable(name="id") int id){
     return actorMapper.selectActorById(id);
}

您的{id} 将是路径变量,将映射到方法的id 参数

【讨论】:

  • 哦,别忘了@PathVariable,这很好! :)
  • @PathVariable 是这里的重要部分
【解决方案2】:

(代表问题作者发布解决方案)

您必须包含@Abhijeet 提到的@PathVariable 注释:

【讨论】:

  • 我不认为这是必要的。您可以看到我已经接受了@Abhijeet 的回答,甚至将其包含在我的原始帖子中。
  • @noogui:是的,问题在于将其包含在您的原始帖子中。 :-) 问题和答案最好在这里分开,尤其是对于数据 API,其中问题和答案帖子被视为单独的可请求实体。 (如果你愿意,你可以自己转发这个答案,我会删除CW版本。
  • (但是,如果你愿意,我们可以删除这个答案——我的目的是把它排除在问题之外)。
【解决方案3】:
    @GetMapping("/actors")
    public Actor selectActorById(@RequestParam("id") int id){
        return actorMapper.selectActorById(id);//use "localhost:9090/actors?id=1" to Visit

    }

【讨论】:

    猜你喜欢
    • 2016-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多