MyBatis之helloMybatis

HelloMybatis

新建空maven项目,导入依赖

<dependency>
    <!--mysql驱动-->
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.48</version>
</dependency>
<dependency>
    <!--mybatis官网-->
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.2</version>
</dependency>
<dependency>
    <!-- junit测试-->
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>

配置resources /mybais-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>
    <!--数据源-->
    <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:3306/mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=utf-8"/>
                <property name="username" value="root"/>
                <property name="password" value="admin"/>
            </dataSource>
        </environment>
    </environments>
    <!--mapper注入mybatis-->
    <mappers>
        <mapper resource="com/ssl/dao/UserMapper.xml"/>
    </mappers>
</configuration>

编写工厂工具类
public class MyBatisUtil {
    /**
     * 提升sqlSessionFactory作用域,便于全局使用
     */
    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            /*
            使用Mybatis第一步,获取sqlSessionFactory对象
             */
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * sqlSessionFactory对象获取SQLSession实例
     */
    public static SqlSession getSqlSession() {
        return sqlSessionFactory.openSession();
    }
}

dao层
public interface UserDao {
    List<User> getUserList();
}
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命名空间=要实现的dao接口-->
<mapper namespace="com.ssl.dao.UserDao">
    <select id="getUserList" resultType="com.ssl.pojo.User">
        select * from mybatis.user
    </select>
</mapper>
测试
public class UserMapperTest {
    @Test
    public void getUserList() {
        //1 获取是sqlSession对象
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        //2 获取的是接口的.class,因为多态
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = userMapper.getUserList();
        for (User user : userList) {
            System.out.println(user);
        }
        //3 建议:最后关闭sqlSession
        sqlSession.close();
    }
}

配置属性

typeAliases(类型别名)

  • 作用:mapper.xml配置resultType时,简化书写
<!--给各种类取别名,简化使用配置-->
<typeAliases>
    <!--方式一:指定类
        <typeAlias alias="User" type="com.ssl.pojo.User"/>
        -->
    <!--方式二;指定包,包中的小写作为别名
                    也可以更改小写名,在类上使用@value(“别名”) -->
    <package name="com.ssl.pojo"/>
</typeAliases>

settings(设置)

mapUnderscoreToCamelCase(重要)	
是否开启驼峰命名自动映射,即从经典数据库列名 A_COLUMN 映射到经典 Java 属性名 aColumn。
默认关闭

logImpl(最重要)	
指定 MyBatis 所用日志的具体实现,未指定时将自动查找。	
SLF4J、LOG4J、STDOUT_LOGGING等,默认关闭


使用log4j需要下载log4j依赖,
STDOUT_LOGGING :掌握,不用导包,mybatis默认配置了,缺点就是只在控制台显示

多对一

有数据库表

CREATE TABLE `student` (
  `id` int(10) NOT NULL,
  `name` varchar(20) DEFAULT NULL,
  `tid` int(10) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `fktid` (`tid`),
  CONSTRAINT `fktid` FOREIGN KEY (`tid`) REFERENCES `teacher` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `teacher` (
  `id` int(10) NOT NULL,
  `name` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

学生表关联老师表

对于学生,多个学生关联一个老师,为多对一

实体类(set/get/toString/有参无参构造自己补上)

public class Student {
    private Integer id;
    private String name;
    //需要关联一个老师类
    private Teacher teacher;
}
public class Teacher {
    private int id;
    private String name;
}

连表查询

<!--方式二:按照结果嵌套处理 = 联表查询-->
<select id="getStudents1" resultMap="resultStudents1">
    select  s.id sid,s.name sname,t.name tname
    from student s,teacher t
    where s.tid = t.id;
</select>
上面查询语句结果集是resultMap,根据id对应到下面这个
<resultMap id="resultStudents1" type="student">
    本质上是student类型(实体类)
    <result property="id" column="sid"/>
    <result property="name" column="sname"/>
    student实体类的 teacher属性也是一个实体类
    <association property="teacher" javaType="teacher">
        <result property="name" column="tname"/>
    </association>
</resultMap>

一对多

同样的sql表格

不同的pojo 对于老师而言,一个老师包含很多学生的集合

public class Student {
    private Integer id;
    private String name;
    private int tid;
}
public class Teacher {
    private int id;
    private String name;
    //一对多的集合
    private List<Student> students;
}

连表查询

<!--联表查询:按结果嵌套查询-->
<select id="getTeacher1" resultMap="teacherAndStudent">
    select  s.id sid,s.name sname,t.name tname,t.id tid
    from mybatis.teacher t,mybatis.student s
    where s.tid=t.id and t.id =#{id}
</select>

<resultMap id="teacherAndStudent" type="teacher">
    <result property="id" column="tid"/>
    <result property="name" column="tname"/>
    <!--集合对象用collection绑定,javaType是返回单个属性,不能返回集合,
返回属性是集合用ofType绑定-->
    <collection property="students" ofType="student">
        <result property="id" column="sid"/>
        <result property="name" column="sname"/>
        <result property="tid" column="tid"/>
    </collection>
</resultMap>

动态sql

看几个案例就懂

<!--if:通过where直接使用/直接使用if判断,但是不推荐。原理:如果test存在,就自动加上where -->
<select id="queryBlogByWhere" parameterType="map" resultType="Blog">
    select * from mybatis.blog
    <where>
        <if test="id !=null">
            id like #{id}
        </if>
        <if test="views !=null">
            and views like #{views}
        </if>
    </where>
</select>
<update id="updateAuthorIfNecessary">
  update Author
    <set>
      <if test="username != null">username=#{username},</if>
      <if test="password != null">password=#{password},</if>
      <if test="email != null">email=#{email},</if>
      <if test="bio != null">bio=#{bio}</if>
    </set>
  where id=#{id}
</update>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值