Search code examples
mysqlspringspring-bootmybatisibatis

How to Get Specific Object Using SelectById(object_id) in SpringBoot-MyBatis-MySQL?


I managed to "get all objects" by creating a SELECT statement in SpringBoot-MyBatis backend like:

AppRestController.java

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

When you type "localhost:9090/actors" in the browser, it will return all actor objects from my MySQL DB. That's good. Now I want to take its complexity up a notch.

I want to fetch a single object by it's actor_id like:

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

Notice my @GetMapping. What I want to do is when I type something like "localhost:9090/actors/1" in the browser, it will return actor object from database with id = 1, and so forth.

Here are the relevant files.

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);
}

Thanks for your help. Update:

so I did change

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

to

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

Apparently, no errors, but Im getting a blank screen. Why? There is a data from my MySQL DB whose actor_id is equal to 1.

enter image description here


Solution

  • Change your get mapping as follow:

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

    Your {id} will be path variable which will be mapped to id parameter of method