Mybatis入门02

ResultMap实现数据库和实体类的属性映射

resultMap专门处理数据库和实体类的映射,其中的column属性是数据库的字段,property对应的是实体类的属性。在写相关sql语句时,按照数据库的字段编写,返回实体类时会根据resultMap进行映射。
ps:这里的的属性由之前的resultType改为resultMap

<resultMap id="UserMap" type="User">
    <!-- id为主键 -->
    <id column="id" property="id"/>
    <!-- column是数据库表的列名 , property是对应实体类的属性名 -->
    <result column="name" property="name"/>
    <result column="pwd" property="password"/>
</resultMap>

<select id="selectUserById" resultMap="UserMap">
    select id , name , pwd from user where id = #{id}
</select>

使用sql语句的limit关键字实现分页

使用limit前,先熟悉一下limit相关的sql语句

SELECT * FROM table LIMIT stratIndex,pageSize

SELECT * FROM table LIMIT 5,10; // 检索记录行 6-15

#如果只给定一个参数,它表示返回最大的记录行数目:   
SELECT * FROM table LIMIT 5; //检索前 5 个记录行

那么对应的UserDao接口,和UserDao.xml文件如下

//分页查询
List<User> getUserByLimit(Map<String,Integer>map);
<select id="getUserByLimit" resultType="user" parameterType="map">
        select * from book.user limit #{startIndex},#{pageSize};
</select>

db.properties文件连接数据库

连接数据库的操作也可以利用db.properties导入到xml文件中进行配置

db.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/book
username=book
password=123456

config.xml

<!--    导入properties文件-->
<properties resource="db.properties"/>

<!--    编写environment时,value值使用类似 ${} 的形式引入properties中配置好的值-->
<environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${pwd}"/>
            </dataSource>
        </environment>
</environments>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值