为了账号安全,请及时绑定邮箱和手机立即绑定

我的mybatis学习记录。

标签:
Java

配置运行环境
1.创建Mybatis核心配置文件SqlMapConfig.xml

<configuration>
    //对实体类进行扫描,并且创建别名
    <typeAliases>
        <package name="com.melon.entity"/>
    </typeAliases>
    <environments default="development">
        <environment id="development">
            //使用JDBC的事务管理
            <transactionManager type="JDBC"/>
            //配置数据源
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis1"/>
                <property name="username" value="root"/>
                <property name="password" value="1"/>
            </dataSource>
        </environment>
    </environments>
    //指定Mapper所在路径
    <mappers>
        <mapper resource="com/melon/mapper/orderMapper.xml"/>
    </mappers>
</configuration>

2.配置orderMapper.xml

    //namespace代表这个mapper的命名空间,如果用mapper代理开发直接填写接口的全路径,也可以自定义
    <mapper namespace="com.melon.mapper.UserMapper(userMapper)">
    //id为该sql语句的唯一标识符
    //parameterType是传入sql语句的参数类型
    //resultType表示查询结果返回的类型
    //#{}表示一个占位符,其中的id代表传入的参数名称,如果是简单类型,名称可以自定义
    <select id="searchUserById" parameterType="int" resultType="user">
        select * from user where id = #{id}
    </select>
//测试
    public class MyBatisFirstTest{
        @Test
        public void searchUserById(){
            //指定SqlMapConfig.xml文件位置
            String resource = Resources.getResourceAsStream("sqlMapConfig.xml");
            //将mybatis的配置信息转化成流
            InputStream inputStream = Resources.getResourceAsStream(resource);
            //创建SqlSessionFactory对象
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            Session session = sqlSessionFactory.openSession();
            //需要传入两个参数,一个是使用的sql语句id,一个是sql语句需要传入的参数
            //指定sql语句前面需要加上命名空间名称
            User user = session.selectOne("userMapper.searchUserById",1);
            System.out.println(user);
        }
    }

Mapper代理方法

//创建OrderMapper.java
public Interface OrderMapper{
    //方法名称要和所使用的sql语句id一样
    public User searchUserById(int id);
}
//测试
    public class MyBatisFirstTest{
        @Test
        public void searchUserById(){
            //指定SqlMapConfig.xml文件位置
            String resource = Resources.getResourceAsStream("sqlMapConfig.xml");
            //将mybatis的配置信息转化成流
            InputStream inputStream = Resources.getResourceAsStream(resource);
            //创建SqlSessionFactory对象
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            Session session = sqlSessionFactory.openSession();
            OrderMapper orderMapper = session.getMapper(OrderMapper.class);
            User user = orderMapper.searchUserById(1);
            System.out.println(user);
        }
    }

使用拼接串符号实现模糊查询

//在Mapper中创建sql语句
    <select id="searchUserByName" parameterType="String" resultType="user">
        //如果${}中接收的是简单类型参数,只能用value
        select * from user where name like '%${value}%'
    </select>
//测试
    public void searchUserById(){
        String resource = Resources.getResourceAsStream("sqlMapConfig.xml");
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        Session session = sqlSessionFactory.openSession();
        //因为可能返回多条记录,所以使用selectList方法来接收一个list
        List<User> list = session.selectList("userMapper.searchUserByName","melon");
        System.out.println(list);
    }
//插入
    <insert id="insertUser" parameterType="user">
        //#{}中接收实体类的属性名,通过ognl来获取对象的属性
        insert into user (name,password,address,tel) value (#{name},#{password},#{address},#{tel})
    </insert>
//删除
    <delete id="deleteUserById" parameterType="int">
        delete * from user where id = #{}
    </delete>
//更新
    <update id="updateUser" parameterType="user">
        update user set name=#{name},password=#{password},address=#{address},tel=#{tel} where id=#{id}
    </update>

使用resultMap

//用购物信息做例子
<resultMap type="User" id="getUser">
        //id表示user类中唯一标识,property是实体类中参数名,column是查询结果中的字段名
        <id property="id" column="id"/>
        //result是查询结果中映射到实体类的其他字段
        <result property="userName" column="username"/>
        <result property="address" column="address"/>
        <result property="sex" column="sex"/>
        <result property="tel" column="tel"/>
        //collection是表示一个user可能有多个order,所以使用collection标签
        <collection property="orders" ofType="Order">
            <result property="orderId" column="order_id"/>
            //一个order会有多个购物项,同理
            <collection property="orderDetails" ofType="OrderDetail">
                <result property="itemNum" column="item_num"/>
                //一个购物项对应一个商品,所以使用association标签
                <association property="item" javaType="Item">
                    <result property="name" column="item_name"/>
                    <result property="price" column="item_price"/>
                </association>
            </collection>
        </collection>
    </resultMap>

动态sql

<sql id="sql1">
    <if test="user.sex != null">
        and sex = #{user.sex}
    </if>
    <if test="user.name != null">
        and name like '%${user.name}%'
    </if>
</sql>

<select>
    select * from user
    <where>
        //where标签会自动去除if条件里面第一个and
        //指定引用的sql片段的id,如果该sql片段不在本mapper文件中,要加上namespace
        <include refid="sql1"></include>
    </where>
</select>

//foreach标签
//用foreach实现以下片段select * from user where id in (1,2,3)
<foreach collection="ids" item="id" open="in(" close=")" separator=",">
    //每次遍历需要拼接的串
    #{id}
</foreach>
点击查看更多内容
2人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消