美文网首页
mybatis的三种映射方式

mybatis的三种映射方式

作者: fatshi | 来源:发表于2022-11-21 14:58 被阅读0次

【参考】https://blog.csdn.net/qq_17690301/article/details/104030667

1. 纯XML配置

mybatis-config.xml中有如下关键配置,关键是mappers

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>    
    ...
    <mappers>
        <mapper resource="com/pojo/Product.xml"/>
    </mappers>
    ...
</configuration>

com/pojo/Product.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="com.pojo">

    <select id="listProduct" resultType="Product">
        select * from product_
    </select>
    
    <select id="selectOneProduct" parameterType="_int" resultType="Product">
        select * from product_ where id = #{id}
    </select>
    
</mapper>

2. 基于xml的接口映射

首先要配置mappers,和上一步一样。
接下来要创建接口:

public interface ProductMapper {
    
    List<Product> listProduct();

    Product get(int id);
    
}

创建映射XML, ProductMapper.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="com.mapper.ProductMapper">

    <select id="listProduct" resultType="Product">
        select * from product_
    </select>
    
    <select id="get" parameterType="_int" resultType="Product">
        select * from product_ where id = #{id}
    </select>
    
</mapper>

3. 基于注解的接口映射

配置mybatis-config.xml,注意mappers:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    ...
    <mappers>
        <mapper class="com.mapper.ProductMapper"/>
    </mappers>
    ...
</configuration>

创建接口ProductMapper.java

@Mapper
public interface ProductMapper {
    
    @Select("select * from product_")
    List<Product> listProduct();

    @Select("select * from product_ where id=#{id}")
    Product get(int id);
    
}

相关文章

网友评论

      本文标题:mybatis的三种映射方式

      本文链接:https://www.haomeiwen.com/subject/kpcnxdtx.html