如何写选择标签形式mybatis选择

时间:2015-06-04 09:48:48

标签: java mybatis

如果我有课

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

dao界面

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

数据库中的表

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

我想知道如何在mybatis中为selectOne方法编写sqlMapper!

2 个答案:

答案 0 :(得分:1)

你可以这样写 -

    <?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>

答案 1 :(得分:1)

这是注释的另一个选择:

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>

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