ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

myBatis3 笔记

2022-06-14 13:31:41  阅读:156  来源: 互联网

标签:name myBatis3 笔记 id public sqlSession mybatis log4j


mybatis 3

官网手册 : https://mybatis.org/mybatis-3/zh/getting-started.html**


一.创建一个Mybatis 应用

1.创建mybatis工具类 mybatisUtls

mybatisUtls.java

//sqlSessionFactory     -->   sqlSession
public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
             sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();

    }
}

2.mybatis被动需要核心配置 mybatis-config.xml

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>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url"
                          value="jdbc:mysql:///mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>

    </environments>


    <!--每一个Mapper. XML都需要在Mybatis核心配置文件中注册! -->
    <mappers>
        <mapper resource="com/kuang/dao/UserMapper.xml"/>
    </mappers>
</configuration>

3.实体类 pojo.User

user.java

public class User {
    private int id;
    private String name;
    private String pwd;

    public User() {
    }

    public User(int id, String name, String pwd) {
        this.id = id;
        this.name = name;
        this.pwd = pwd;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    @Override
    public String toString() {
        return "user{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", pwd='" + pwd + '\'' +
                '}';
    }
}

4.接口 UserDao,后写Mapper.xml

接口userDao

public interface UserDao {
    List<User>  getUserList();
}

Usermapper.xml

<?xml version="1.0" encoding="utf8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!--绑定一个对应的dao or mapper 接口-->
<mapper namespace="com.kuang.dao.UserDao">
<!--    select  查询语句-->
    <select id="getUserList" resultType="com.kuang.pojo.User">
        select * from  mybatis.user
    </select>


</mapper>

5.写测试类UseraoTest

public class UserDaoTest {
    @Test
    public void test(){
//       第一步 获得sqlSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        try {
            //    方式一:  getMapper   极其推荐
            UserDao userDao= sqlSession.getMapper(UserDao.class);
            List<User> userList=userDao.getUserList();
            for (User user : userList) {
                System.out.println(user);

            }


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }


//      方式二 :  不推荐 老了
//        List<User> userList = sqlSession.selectList("com.kuang.dao.UserDao.getUserList");




    }
}

mybatis 核心配置

路径:src/main/resources/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>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url"
                          value="jdbc:mysql:///mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>

    </environments>


    <!--每一个Mapper. XML都需要在Mybatis核心配置文件中注册! -->
    <mappers>
        <mapper resource="com/kuang/dao/UserMapper.xml"/>
    </mappers>
</configuration>

注意点

找不到Mapper.xml 报错;在父 子 pom.xml文件中加如下code

资源扫描器插件

<!--在build中配置resources,来防止我们资源导出失败的问题-->
    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

dao接口

public interface UserDao {
    List<User>  getUserList();
}

●接口实现类由原来的UserDaolmpl转变为-个Mapper配置文件.

<?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">
<!--绑定一个对应的dao or mapper 接口-->
<mapper namespace="com.kuang.dao.UserDao">
<!--    select  查询语句-->

    <select id="getUserList" resultType="com.kuang.pojo.User">
        select * from mybatis.user
    </select>


</mapper>

CROD

1.namespace

中的包名 要与 dao/mapper 接口的包名 一致

2.select

  • id : 就是对应的namespace中的方法名;
  • resultType:Sql语句执行的返回值!
  • parameterType :参数类型!
  1. 编写接口

    //    查询所有用户
        List<User>  getUserList();
    //    select byId
        User getUserById(int id);
    
  2. 编写对应的mapper中的SQL语句

    <!--绑定一个对应的dao or mapper 接口-->
    <mapper namespace="com.kuang.dao.UserMapper">
    <!--    select  查询语句-->
        <select id="getUserList" resultType="com.kuang.pojo.User">
            select * from  mybatis.user
        </select>
        <select id="getUserById" parameterType="int" resultType="com.kuang.pojo.User">
            select * from  mybatis.user where id =#{id}
        </select>
    
  3. 测试

       @Test   //Test 必须写这个注解
        public void list(){
    //       第一步 获得sqlSession对象
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            try {
                //    方式一:  getMapper   极其推荐
                UserMapper userDao= sqlSession.getMapper(UserMapper.class);
                List<User> userList=userDao.getUserList();
                for (User user : userList) {
                    System.out.println(user);
    
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                sqlSession.close();
            }
    //      方式二 :  不推荐 老了
    //        List<User> userList = sqlSession.selectList("com.kuang.dao.UserDao.getUserList");
    
        }
        
        @Test  
        public void getUserById(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.getUserById(12);
        System.out.println(user);
    
    
        sqlSession.close();
    }
    

3.insert(mapper.xml)

<!--insert  -->
    <insert id="addUser" parameterType="com.kuang.pojo.User" >
    insert into mybatis.user(id, name, pwd) value (#{id},#{name},#{pwd})

    </insert>

4.update

<!--    update   -->
    <update id="updateUser" parameterType="com.kuang.pojo.User" >
        update mybatis.user set name =#{name},pwd=#{pwd} where id = #{id};

    </update>

5.delete

<!--    delete  -->
    <delete id="deleteUser" parameterType="com.kuang.pojo.User" >
    delete from mybatis.user where id =#{id}

    </delete>

注意点:

  • 增 删 改 需要提交事务

  • resource绑定mapper, 需要使用路径 / /

    <!--每一个Mapper. XML都需要在Mybatis核心配置文件中注册! -->
    <mappers>
        <mapper resource="com/kuang/dao/UserMapper.xml"/>
    </mappers>
    
    • 程序配置文件必须符合规范!
    • NullPointerException,没有注册到资源!
    • 输出的xm|文件中存在中文乱码问题!
    • maven资源没有导出问题!

万能Mapper

假设,我们的实体类,或者数据库中的表,字段或者参数过多,我们应当考虑使用Map!

// 万能的Map
   int addUser2(Map<String,Object> map);
<!--insert    万能Map-->
<insert id="addUser2" parameterType="map" >
    insert into mybatis.user(id, name, pwd) value (#{userid},#{username},#{password})

</insert>
    @Test
    public void addUser2(){
//          万能Map      增删改  需要提交事务
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
       Map<String, Object> map = new HashMap<>();
       map.put("userid", 5);
       map.put("username","hello");
       map.put("password","helio0");

       mapper.addUser2(map);
        sqlSession.commit();  // 增删改  需要提交事务
        sqlSession.close();
    }
  1. Map传递参数,直接在sq|中取出key即可! [parameterType="map"]
  2. 对象传递参数,直接在sq|中取对象的属性即可! [parameterType="Objet"]
  3. 只有一个基本类型参数的情况下,可以直接在sq|中取到!
  4. 多个参数用Map,或者注解!

模糊查询 怎么写

  • 在SQL拼接中使用通配符
<select id="getUserLike" resultType="com.kuang.pojo.User">
select * from mybatis.user where name like "#" #{ value} "#"

</select>

​ 容易存在SQL注入,

  • java执行时使用通配符
    @Test
    public void getUserLike(){
//       第一步 获得sqlSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper= sqlSession.getMapper(UserMapper.class);
        List<User> userList = mapper.getUserLike("%李%");
        for (User user : userList) {
            System.out.println(user);

        }
        sqlSession.close();


    }

让用户只能传稳定的值

配置解析

1.MyBatis 的配置文件包含了会深深影响 MyBatis 行为的设置和属性信息。

configuration(配置)

2、环境配置(environments)

MyBatis可以配置成适应多种环境
不过要记住:尽管可以配置多个环境,但每个SqISessionFactory实例只能选择1种环境。
学会使用配置多套运行环境!
Mybatis默认的事务管理器就是JDBC,连接池: POOLED

resultMap

结果集映射

1   name id pwd
2   name id  password

UserMapper.xml

<!--    结果集映射          sql中 列  --> User类中的属性   -->
    <resultMap id="UserMap" type="User">
        <result column="id" property="id"/>
        <result column="name" property="name"/>
        <!--suppress MybatisXMapperXmlInspection -->
        <result column="pwd" property="password" />
    </resultMap>





    <select id="getUserById" parameterType="int" resultMap="UserMap">
        select * from  mybatis.user where id =#{id}
    </select>

6.日志

如果一一个数据库操作,出现了异常,我们需要排错。日志就是最好的助手!
曾经: sout、 debug
现在:日志工厂!

LOG4J(mybatis 3.5.9 起废弃) LOG4J2

  1. STDOUT_LOGGING

image-20220602145007962

  1. LOG4J

    导包

    <!-- https://mvnrepository.com/artifact/log4j/log4j -->
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
    
    

​ log4j.properties

### set log levels ###
log4j.rootLogger = DEBUG,console,file

### 输出到控制台 ###
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.Threshold = DEBUG
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern = [%c]-%m%n

### 输出到日志文件 ###
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./log/hou.log
log4j.appender.file.MaxFileSize=10mb 
log4j.appender.file.Threshold=DEBUG 
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n

# 日志输出级别
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

mybatis-config.xml

 <settings>
        <setting name="logImpl" value="LOG4J"/>

<!--    标准的日志    <setting name="logImpl" value="STDOUT_LOGGING"/>   -->
    </settings>

log4j 简单使用

  1. 在要使用Log4j的类中,导入包 import org.apache.log4j.Logger;

  2. 日志对象,参数为当前类的class

       static Logger logger = Logger.getLogger(UserDaoTest.class);
    
    
  3. 日志级别

    logger.info("info 进入testLog4j");
    logger.debug("info 进入testLog4j");
    logger.error("info 进入testLog4j");
    

分页

select * from  mybatis.user limit stratIndex,endIndex 
select * from  mybatis.user limit 3;   [0,n]
  1. limit 分页

  2. RowBounds实现

  3. 分页插件

    image-20220603151843419image-20220603151844401

了解即可,万一以后公司的架构师,说要使用,你需要知道它是什么东西!|

使用注解开发

  1. 面向接口编程

-大家之前都学过面向对象编程,也学习过接口,但在真正的开发中,很多时候我们会选择面向接口编程

  • **根本原因:
    解耦 ,可拓展,提高复用,分层开发中,上层不用管具体的实现,大家都遵守共同的标准,使得开发变得容易,规范性更好,在一一个面向对象的系统中,系统的各种功能是由许许多多的不同对象协作完成的。在这种情况下,各个对象内部
    是如何实现自己的,对系统设计人员来讲就不那么重要了;而各个对象之间的协作关系则成为系统设计的关键。小到不同类之间的通信,大到各模块之间的交互,在系统设计之初都是要着重考虑的,这也是系统设计的主要工作内容。面向接口编程就是指按照这种思想来编程。

关于接口的理解

-接口从更深层次的理解,应是定义(规范,约束)与实现(名实分离的原则)的分离。
. 接口的本身反映了系统设计人员对系统的抽象理解。
-接口应有两类:
-第一类是对一个个体的抽象,它可对应为- -个抽象体(abstract class);
-第二类是对一一个个体某一 方面的抽象,即形成一个抽象面(interface) ;
-一个体有可能有多个抽象面。抽象体与抽象面是有区别的。

三个面向区别

面向对象是指,我们考虑问题时,以对象为单位,考虑它的属性及方法.
面向过程是指,我们考虑问题时,以一个具体的流程(事务过程)为单位,考虑它的实现.
-接口设计与非接口设计是针对复用技术而言的,与面向对象(过程)不是一个问题更多的体现就是对系统整体的架构

  1. 适用注解开发

​ 本质:反射机制实现
​ 底层:动态代理!

image-20220603154744329

  1. 注解 CROD

[注意:我们必须要将 接口注册绑定到我们的核心配置文件中! ]

关于@Param("uid")

●基本类型的参数或者String类型,需要加上
●引用类型不需要加
●如果只有一个基本类型的话,可以忽略,但是建议大家都加上!
●我们在SQL中引用的就是我们这里的@Param()中设定的属性名!

#{} (推荐 ,可以防止sql注入, 跟Statement和Prestatement) ${} 区别

Lombok

1 进入设置安装lombok 插件,

2 导包

<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.22</version>
    <scope>provided</scope>
</dependency>

3 实体类上加注解即可

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private int id;
    private String name;
    private String password;

}
@Getter and @Setter
@FieldNameConstants
@ToString
@EqualsAndHashCode
@AllArgsConstructor, @RequiredArgsConstructor and @NoArgsConstructor
@Log, @Log4j, @Log4j2, @Slf4j, @XSlf4j, @CommonsLog, @JBossLog, @Flogger, @CustomLog
@Data
@Builder
@SuperBuilder
@Singular
@Delegate
@Value
@Accessors
@Wither
@With
@SneakyThrows
@StandardException
@val
@var
experimental @var
@UtilityClass
Lombok config system
@Data:  生成 无参构造,get、 set、 tostring. hashcode, equals

优点:

1.能通过注解的形式自动生成构造器、getter/setter. equals. hashcode、 toString等方法, 提高了-定的开发效率
2.让代码变得简洁,不用过多的去关注相应的方法
3.属性做修改时,也简化了维护为这些属性所生成的getter/setter方法等

缺点:

1.不支持多种参数构造器的重载如
2.虽然省去了手动创建getter/setter方法的麻烦,但大大降低了源代码的可读性和完整性,降低了阅读源代码的舒适度

总结

Lombok虽然有很多优点,但Lombok更类似于一种IDE插件, 项目也需要依赖相应的jar包。Lombok依赖jar包是因为编译时要用它
的注解,为什么说它又类似插件?因为在使用时,eclipse或IntelliJ IDEA都需要安装相应的插件,在编译器编译时通过操作AST (抽象
语法树)改变字节码生成,变向的就是说它在改变java语法。它不像spring的依赖注入或者mybatis的ORM-样是运行时的特性,而是编译时的特性。这里我个人最感觉不爽的地方就是对插件的依赖!因为Lombok只是省去了一些人工生成代码的麻烦, 但IDE都有快捷键来协助生成getter/setter等方法, 也非常方便。
知乎上有位大神发表过对Lombok的一些看法:
这是一种低级趣味的插件,不建议使用。JAVA发展到今天,各种插件层出不穷,如何甄别各种插件的优劣?能从架构上优化你的设计的,能提高应用程序性能的,实现高度封装可扩展的...,像lombok这种, 像这种插件,已经不仅仅是插件了,改变了你如何编写源码,事实上,少去了的代码,你写.上去又如何?如果JAVA家族到处充斥这样的东西, 那只不过是一坨披着金属颜色的屎, 迟早会被其它的语言取代。

多对一

●多个学生,对应-一个老师
●对于学生这边而言,关联 ..多个学生,关联一个老师 [多对一 ]
●对于老师而言,集合,- -个老师,有很多学生 [一对多]

测试环境搭建
1.导入lombok
2.新建实体类Teacher, Student
3.建立Mapper接口
4.建立Mapper .XML文件
5.在核心配置文件中绑定注册我们的Mapper接口或者文件! [方式很多, 随心选]
6.测试查询是否能够成功!

  1. 子查询
<!--    =======================================-->
<!--    思路:
    1.查询所有的学生信息
    2.根据查询出来的学生的tid,寻找对应的老师!      子查询
-->
    <select id="getStudent" resultMap="StudentTeacher">
    select * from student
    </select>

    <resultMap id="StudentTeacher" type="Student">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
        <!--复杂的属性(teacher属性),我们需要单独处理   对象:     association         集合:     collection    -->
        <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
    </resultMap>

    <select id="getTeacher" resultType="Teacher">
        select * from teacher where id = #{id}
    </select>
  1. 嵌套查询(推荐)
<!--    按照结果嵌套处理     推荐 -->
    <select id="getStudent2" resultMap="StudentTeacher2">
        select s.id sid,s.name sname ,t.name tname
        from student s, teacher t
        where s.tid = t.id;
    </select>
    <resultMap id="StudentTeacher2" type="Student">
        <result property="id" column="sid"/>
        <result property="name" column="sname"/>
        <association property="teacher" javaType="teacher">
            <result property="name" column="tname"/>
        </association>
    </resultMap>

一对多

实体类

@Data
public class Teacher {
    private int id;
    private String name;
    private List<Student> students;


}
@Data
public class Student {
    private int id;
    private String name;
    //学生需要关联一个老师!
    private int tid;


}

按照结果嵌套查询(推荐 ,不易出错)

<!--  按照结果嵌套查询-->
    <select id="getTeacher" resultMap="TeacherStudent">
        SELECT s.id sid, s.name sname, t.name tname,t.id tid
        FROM student s, teacher t
        WHERE s.tid = t.id AND t.id = #{tid}
    </select>
    
    <resultMap id="TeacherStudent" type="Teacher">
        <result property="id" column="tid"/>
        <result property="name" column="tname"/>
        <collection property="students" ofType="student">
            <result property="id" column="sid"/>
            <result property="name" column="sname"/>
            <result property="tid" column="tid"/>
        </collection>
    </resultMap>
    

子查询处理

<select id="getTeacher2" resultMap="TeacherStudent2">
    select * from mybatis.teacher where id =#{tid};
</select>
<resultMap id="TeacherStudent2" type="teacher">
    <collection property="students" javaType="ArrayList" ofType="Student" select="getStudentByTeacherId" column="id"/>
</resultMap>
<select id="getStudentByTeacherId" resultType="Student">
    select * from mybatis.student where tid =#{tid};
</select>

小结

1.关联- association [多对一 ]
2.集合- collection [- -对多]

​ javaType & ofType

  • JavaType用来指定实体类中属性的类型

  • ofType用来指定映射到List或者集合中的pojo类型,泛型中的约束类型!

注意点:

●保证SQL的可读性,尽量保证通俗易懂
●注意一对多和多对- -中,属性名和字段的问题!
●如果问题不好排查错误,可以使用日志,建议使用Log4j

面试高频

●Mysq引擎

●InnoDB底 层原
●索引
●索引优化!

动态SQL

创建一一个基础工程

1.导包
2.编写配置文件
3.编写实体类

@Data
public class Blog {
    private int id;
    private String title;
    private String auther;
    private Data createDate;
    private int views;

}

4.编写实体类对应Mapper接口和Mapper.XML文件

标签:name,myBatis3,笔记,id,public,sqlSession,mybatis,log4j
来源: https://www.cnblogs.com/mikasa9826/p/16374314.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有