狂神mybatis笔记入门学习及问题解决

Mybatis入门学习

一、简介

  • myBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。

  • MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。

  • MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。

    如何获取mybatis:

GitHub:https://github.com/mybatis/mybatis-3/releases

maven:https://mvnrepository.com/artifact/org.mybatis/mybatis

官网:https://mybatis.org/mybatis-3/zh/index.html

二、第一个Mybatis程序

2.1、导入依赖

mybatis

<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.6</version>
</dependency>

junit

mysql

2.2、编写mybatis核心配置文件

XML 配置文件中包含了对 MyBatis 系统的核心设置,包括获取数据库连接实例的数据源(DataSource)以及决定事务作用域和控制方式的事务管理器(TransactionManager)

<?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核心配置文件-->
<configuration>
  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC"/>
      <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>
    <!--每一个Mapper文件都需要在Mybatis核心配置文件中注册-->
  <mappers>
    <mapper resource="org/mybatis/example/BlogMapper.xml"/>
  </mappers>
</configuration>
2.3连接数据库出现下面问题解决方案:
java.lang.RuntimeException: com.mysql.cj.exceptions.InvalidConnectionAttributeException: The server time zone value 'Öйú±ê׼ʱ¼ä' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.
            at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
            at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
            at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
            at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
            at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:61)
            at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:85)
            at com.mysql.cj.util.TimeUtil.getCanonicalTimezone(TimeUtil.java:132)
            at com.mysql.cj.protocol.a.NativePro... (show balloon)

大概原因:

JDBC驱动程序的5.2版本与UTC时区配合使用,必须在连接字符串中明确指定serverTimezone。

2.4、解决方法:
jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC

注明:mybatis为连接的数据库,比如你创建的数据库是test1,则这里使用test1!!!!

在这里插入图片描述

2.5、创建mybatis工具类
public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;
        static {
            try {
                //获取SqlSessionFactory对象
                String resource = "mybatis-config.xml";
                InputStream inputStream = Resources.getResourceAsStream(resource);
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    //既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
    public static SqlSession getSqlSession(){
        //SqlSession sqlSession = sqlSessionFactory.openSession();
        //return sqlSession;
        return sqlSessionFactory.openSession();

    }
}
2.6、编写实体类
2.6.1、实体类
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;
    }
}

2.6.2、DAO接口
public interface UserDao {
    List<User> getUserList();
}

  • 接口实现类由原来的UserDaoimpl转换为一个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">
    <!--namespace=绑定一个对应的Dao/mapper接口-->
    <mapper namespace="com.LH.Dao.UserDao">
    <!--<mapper namespace="org.mybatis.example.BlogMapper">改为如上-->
    <!--<select id="selectBlog" resultType="Blog">-->
    <!-- select * from Blog where id = #{id}-->
    <!--</select>-->
    <!--select查询语句-->
        <select id="getUserList" resultType="com.LH.pojo.User">
            select *from mybatis.user;
        </select>
    </mapper>
    
2.7测试
2.7.1、注意点:
org.apache.ibatis.binding.BindingException: Type interface com.LH.Dao.UserDao is not known to the MapperRegistry.

MapperRegistry

2.7.2、junit测试

注意点:org.apache.ibatis.binding.BindingException: Type interface com.kuang.dao.UserDao is not known to the MapperRegistry.

2.7.3、MapperRegistry是什么?

核心配置表文件注册mappers

所以一定要记得注册!!!!!

在这里插入图片描述

2.8、中间所有遇到的问题
2.8.1、问题:
  • 3 字节的 UTF-8 序列的字节 3 无效
  • can not find resource com/LH/Dao/mybatis-config.xml
WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
  • 空指针异常
  • Error building SqlSession
  • Could not find resource com.mycode.dao.UserMapper.xml
2.8.2、我的解决方案为:

1.删除pomxml中的所有中文

2.在pom中添加下面代码:(放在project中即可)

<!--在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>

Mon Nov 09 17:05:33 GMT+08:00 2020 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.

在URL中加入&useSSL=false
在这里插入图片描述

在mybatis-config.xml中添加(注意:这一句不能加在末尾,不然会报错)

&amp;useSSL=false

4.在这里插入图片描述

改为com.LH.pojo.User即可
在这里插入图片描述

5.https://blog.csdn.net/qq_45615417/article/details/104735662 这篇博客应该可以非常细致的讲解这个问题

以上基本问题大致能够解决了

三、CRUD

1.namespace
2.Select
  • namespace中的包名要和Dao/Mapper解口的包名一致

  • id:就是对应的namespace中的方法名

  • resultType:Sql执行语句的返回值!

  • parameterType:参数类型!

1.编写对应的接口

//根据ID查询用户
    User getUserById(int id);

2.编写对应的mapper中的sql语句

<select id="getUserById" resultType="com.LH.pojo.User">
        select * from mybatis.user where id=#{id};
    </select>

3.测试

    @Test
    public void getUserById(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User userById = mapper.getUserById(1);
        System.out.println(userById);
        sqlSession.close();
    }

3.add
 //增加删除改变都需要开启事物
    @Test
    public void addUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.addUser(new User(4,"zhuo","45454"));
        //提交事物
        sqlSession.commit();
        sqlSession.close();
    }
4.update
   @Test
    public void updateUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.updateUser(new User(2,"ming","151561"));
        sqlSession.commit();
        sqlSession.close();
    }
5.delete
 @Test
    public void deleteUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.deleteUser(1);
        sqlSession.commit();
        sqlSession.close();
    }
}

注意点:增删改需要提交事物

6、模糊查询怎么实现

1.java代码执行时传递通配符%%(不推荐使用)

List<User> userLike = mapper.getUserLike("%李%");
  1. 在sql拼接中使用通配符
select *from mybatis.user where name like "%"#{value}"%"

;
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.deleteUser(1);
sqlSession.commit();
sqlSession.close();
}
}


注意点:增删改需要提交事物

####  6、模糊查询怎么实现

1.java代码执行时传递通配符%%(不推荐使用)

```java
List<User> userLike = mapper.getUserLike("%李%");
  1. 在sql拼接中使用通配符
select *from mybatis.user where name like "%"#{value}"%"
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值