java_mybatis总结2

pom.xml

<!-- mybatis核心依赖 -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.5</version>
</dependency>

<!-- mysql连接依赖 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.20</version>
</dependency>

<!-- junit测试 -->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13</version>
    <scope>test</scope>
</dependency>

<!-- log4j日志依赖 -->
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

jdbc.properties


注意mybatis版本>=6.0使用如下驱动,如果<6.0使用com.mysql.jdbc.Driver
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=UTF-8&&serverTimezone=Hongkong&useSSL=false
username=root
password=root

mybatis-config.xml

<?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>
    <!--引入jdbc属性配置-->
    <properties resource="jdbc.properties"></properties>
    <!--mybatis的核心环境配置-->
    <environments default="development">
        <environment id="development">
            <!--
             在 MyBatis 中有两种类型的事务管理器(也就是 type="[JDBC|MANAGED]"):
             JDBC – 这个配置直接使用了 JDBC 的提交和回滚设施
             MANAGED – 这个配置几乎没做什么
             -->
            <transactionManager type="JDBC"/>
            <!--type可选值:UNPOOLED 不使用连接池
                          POOLED使用连接池
                          JNDI 从配置好的JNDI数据源获取连接池-->
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="mapper/UserMapper.xml"/>
    </mappers>
</configuration>

UserMapper.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">
<!--
namespace
用于对SQL语句进行隔离,mapper文件有多个,不同的mapper文件中SQL可能重复,
可以使用namespace进行区分,因此namespace最好保证唯一性,否则没有意义
-->
<mapper namespace="test">

    <!--
    id:sql片段的唯一标识,同一个mapper文件中不能重复
    parameterType:参数类型
    resultType:返回值类型
    -->
    <select id="selectOne" parameterType="int" resultType="com.czxy.mybatis.model.User">
        SELECT
        uid,
        username,
        birthday,
        phone,
        sex,
        address
        FROM `user`
        WHERE uid = #{aa}
    </select>

</mapper>

这写配置文件都在resource目录下存放

测试

public class MyBatisTest {

    @Test
    public void selectOne() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。
        //可以通过 SqlSession 实例来直接执行已映射的 SQL 语句
        SqlSession sqlSession = sqlSessionFactory.openSession();

        //通过 namespace.id的方式确定要执行的SQL片段
        User user = sqlSession.selectOne("test.selectOne",10);
        System.out.println(user);
        //用完后必须管理连接
        sqlSession.close();

    }

}

添加 一条数据可以查看生成主键

<insert id="insertUserAndReturnID" useGeneratedKeys="true" keyProperty="uid">
    INSERT INTO `user`
    (uid,username,birthday,phone,sex,address)
    VALUES(NULL,#{username},#{birthday},#{phone},#{sex},#{address})
</insert>

普通xml和有接口的xml的区别
普通xml的没有接口的mapper namespace 是起一个名字,有接口的mapper的namespace是写写的是接口的相对路径,普通的用于单表,高级的用于多表,高级接口里面方法的名字就是xml的id ,直接调用这个接口里的方法,普通的namespace的名字 加上,需要调用sql自带方法,绑定上。
片段id就是该方法
例子
在这里插入图片描述
传参数类型
一个 参数时,在#{}里面的名字可以和传过来的不一样
多个 参数可以用map ,pojo 但是必须要和#{}里面名字一样

返回的类型 对象 集合 map 个数

resultMap

当查询结果有多个列,并且列名和字段名称不一致时,mybatis无法将结果封装到model对象中,这是需要通过resultMap绑定列和属性关系

动态sql
if 需要加上where 对传入参数的属性值进行判断,结果为true则拼接SQL片段,否则不拼接,容易报错,少用这种

例子

<!--动态SQL - if -->
<select id="selectByNameAndBirthday2" resultType="user">
    select <include refid="baseColumn"></include>
    from `user`
    where
    <if test="username != null and username != ''">
        username like #{username}
    </if>
    <if test="birthday != null">
        AND birthday = #{birthday}
    </if>
</select>

推荐
where 符合条件的判断上 ,不符合条件的进行下一个判断,都不符合查询所有
例子

<!--动态SQL - if where -->
<select id="selectByNameAndBirthday2" resultType="user">
    select <include refid="baseColumn"></include>
    from `user`
    <where>
        <if test="username != null and username != ''">
            username like #{username}
        </if>
        <if test="birthday != null">
            AND birthday = #{birthday}
        </if>
    </where>
</select>

choose 适用于 查询的字段于表的字段不一样 ,但有一定规则能联系上
注意
当比较的值只有一个字符时,mybatis会把值当成char处理,转成数值,汉字是无法直接转成数值的,因此这里要用双引号,表示是字符串
例子

<select id="dynamicSQLChoose" resultType="user">
    select
    <include refid="baseColumn"></include>
    from `user`
    <where>
        <choose>
            <when test='sex != null and sex == "男"'>
                and sex = '1'
            </when>
            <when test='sex != null and sex == "女"'>
                and sex = '2'
            </when>
            <otherwise>
                and sex is not null
            </otherwise>
        </choose>
    </where>
</select>

foreach
类似于java中for循环,主要用于in语句的条件查询

在这里插入图片描述

set
set用于update的动态SQL中。符合条件的就判断,不符合条件的过滤,不会报错
例子

<!--动态sql - update只用if判断的写法-->
<update id="dynamicUpdateUser" >
    UPDATE
    `user`
    <set>
        <if test="username != null and username != ''">
            username = #{username},
        </if>
        <if test="phone != null and phone != ''">
            phone=#{phone},
        </if>
        <if test="sex != null and sex != ''">
            sex = #{sex}
        </if>
    </set>
    WHERE uid = #{uid}
</update>

trim(了解)
不符合条件就会留下and 或 or 除去多余的and ,就是条件没有满足时,不报错
例子
在这里插入图片描述

不符合条件的,会留下逗号 ,可以用trim取出逗号
在这里插入图片描述
适用trim的话可以除去没有符合条件的关键字,或者逗号,关键字包裹在
prefix="" ,去除的逗号包裹在 prefixOverrides=“AND | OR” ,有逗号,关键字等,我只会用前缀

在这里插入图片描述

分页
导入依赖

<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper -->
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>5.1.10</version>
</dependency>

mybatis-config.xml

<plugins>
    <!-- com.github.pagehelper为PageHelper类所在包名 -->
    <plugin interceptor="com.github.pagehelper.PageInterceptor">
        <!-- 选择mysql数据库的分页方式 -->
        <property name="helperDialect" value="mysql"/>
        <property name="rowBoundsWithCount" value="true"/>
    </plugin>
</plugins>

相当于一个查询所有


@Test
public void limitTest(){
    SqlSession session = MyBatisMapperUtils.getSession();
    UserMapper mapper = session.getMapper(UserMapper.class);

    //1. 开启分页 : pageNum 第几页,从1开始, pageSize 每页显示条数
    PageHelper.startPage(1,3);

    //2. 条件查询
    List<User> users = mapper.selectAll();

    //3. 将查询结果交给PageInfo处理
    PageInfo<User> pageInfo = new PageInfo<>(users);
    
    //分页相关结果
    long total = pageInfo.getTotal();       //总条数
    int pageNum = pageInfo.getPageNum();    //当前页
    int pages = pageInfo.getPages();        //总页数
    List<User> pageInfoList = pageInfo.getList();   //当前页数据

    System.out.println("总条数:"+total+" 当前页:"+pageNum+" 总页数"+pages);
    System.out.println("当前页数据....");
    for (User user : pageInfoList) {
        System.out.println(user);
    }

    MyBatisMapperUtils.closeSession();
}

总结
日期 只能用 null 不能用 ’ ’
价格 一般建议用BigDecimal

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值