n3o
n3o

Reputation: 2873

Parameters are not getting subsituted in MyBatis query

The following is my select query in BrandMapper.xml.

<select id="getBrand" parameterType="String" resultMap="brandResult">
    SELECT 
        B.bid as bid, 
        B.bname as bname, 
        B.avg_price as avg_price, 
        B.total_number as total_number, 
        P.pid as pid, 
        P.pname as pname, 
        P.bid as pbid, 
        P.bname as pbname, 
        P.specs as pspecs, 
        P.price as price 
    from Brands B left outer join Products P on P.bid = B.bid 
    where B.bname = #{bname, jdbcType=VARCHAR}
</select>

This is the interface

public interface BrandMapper {
    BrandDAO getBrand(String bname);
}

This is the service class

@Service
public class BrandService {
@Autowired
private BrandMapper brandMapper;
public BrandDAO getBrand(String bname) {
    System.out.println("Inside DBService getBrand");
    return brandMapper.getBrand(bname);
}
}

My problem is that the getBrand function in BrandService returns a null value. If I replace the parameter #{bname} inside the BrandMapper.xml by a hardcoded string it works and returns the correct class. What am I doing wrong here? Is there any logs or anything available where I can see the actual query which is being constructed? Any help is appreciated.

I managed to enable loggin using log4j and this is the query which is getting executed

SELECT B.bid as bid, B.bname as bname, B.avg_price as avg_price, B.total_number as total_number, P.pid as pid, P.pname as pname, P.bid as pbid, P.bname as pbname, P.specs as pspecs, P.price as price from Brands B left outer join Products P on P.bid = B.bid where B.bname = ?

The parameter is not getting replaced. I cant figure out what I am doing wrong here.

Upvotes: 1

Views: 2536

Answers (1)

mrembisz
mrembisz

Reputation: 12880

The question mark is a placeholder in Prepared Statements, the logged query is perfectly fine and looks as expected. The real value should be passed along the query to your database as a separate parameter.

Upvotes: 3

Related Questions