如何写select标签形式mybatis select

how to write select tag form mybatis select

如果我有 class

public class Product {
private int id; 
private String name;
private double price;
private String type;
}

一个dao接口

public interface {
 public Product selectOne(int id);
}

一个 table 在数据库中

T_Product (
id tinyint,
name varchar(50),
price long,
type varchar(30) );

想知道selectOne方法在mybatis中的sqlMapper怎么写!

你可以这样写 -

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

    <mapper namespace="YOUR_INTERFACE_NAME_WITH_PACKAGE_NAME">
        <resultMap type="YOUR_ENITIY_PACKAGE_NAME.Product " id="productMap">
            <result property="id" column="id" />        
            <result property="name" column="name" />
            <result property="price" column="price" />
             <result property="type"    column="type" />
        </resultMap>
         <select id="selectOne" resultMap="productMap">
            select * from product where id = #{id};
        </select>
     </mapper>

这是注释的另一个选项:

public interface ProductMapper{
 @Select( "select id, name, price, tag from Product where id = #{id}" )
 public Product selectOne( @Param("id") int id);
}

这是xml中的另一种写法:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="YOUR_INTERFACE_NAME_WITH_PACKAGE_NAME">
     <select id="selectOne" resultType="Product">
        select id, name, price, tag from Product where id = #{id}
    </select>
</mapper>

不需要结果映射,因为列可以直接映射到对象 属性。