基于Maven的Mybatis入门

一、新建一个Maven项目
基于Maven的Mybatis入门_第1张图片
二、在pom.xml中添加依赖关系

<dependencies>
     <dependency>
        <groupId>org.mybatisgroupId>
        <artifactId>mybatisartifactId>
        <version>3.3.0version>
    dependency>
    <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>5.1.25version>
     dependency>
  dependencies>

三、新建一个mybatis配置文件
基于Maven的Mybatis入门_第2张图片

在配置文件中设置数据库连接池(效率低,真实开发中不适用)以及配置映射关系


            

            <configuration>
                <environments default="development">
                    <environment id="development">
                        <transactionManager type="JDBC" />
                        <dataSource type="POOLED">
                            <property name="driver" value="com.mysql.jdbc.Driver" />
                            <property name="url" value="jdbc:mysql://localhost/test" />
                            <property name="username" value="root" />
                            <property name="password" value="root" />
                        dataSource>
                    environment>
                environments>

                
                <mappers>
                    <mapper resource="com/xingxue/user/GoodsMapper.xml" />
                    <mapper resource="com/xingxue/user/UserMapper.xml" />
                mappers>

            configuration>

sql的配置文件
基于Maven的Mybatis入门_第3张图片



    <mapper namespace="Goods">

        <select id="selectGoodsById" resultType="java.util.HashMap">
            select * from goods where id = #{id}
        select>

        <select id="selectGoodsByPage" resultType="java.util.HashMap">
            select * from goods 
        select>
        
        <select id="updateGoodsByAll">
            UPDATE `test`.`goods`
                SET
                <if test="id != null">
                 `id` = #{id}
                if>
                <if test="name != null">
                 ,`name` = #{name}
                if>
                <if test="price != null">
                 ,`price` = #{price}
                if>
                <if test="statu != null">
                 ,`statu` = #{statu}
                if>
                <if test="date != null">
                 ,`date` = #{date}
                if>
                <if test="typeid != null">
                 ,`typeid` = #{typeid}
                if>
                <if test="num != null">
                 ,`num` = #{num}
                if>
            WHERE
                (`id` = #{id})
        select>

        <select id="updateGoods">
            update goods set name='zhangsan' where id in
            <foreach collection="list" open="(" separator="," close=")" item="ids">
                #{ids}
            foreach>
        select>

    mapper>   

你可能感兴趣的:(Mybatis)