mybatis-note-笔记

每日一图

Mysql连接出错

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

有可能是mysql没有启动出错

Mybatis第一个代码:

设置POM,配置jar


这里是正确的dependency的maven

<dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.11</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

配置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://localhost:3306/mybatis?characterEncoding=utf8&amp;useSSL=false&amp;serverTimezone=UTC&amp;rewriteBatchedStatements=true"/>
                <property name="username" value="root"/>
                <property name="password" value="Mysql2486"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="userMapper.xml"/>
    </mappers>
</configuration>

创建DAO、UTILS、POJO

Idea里面可以看到这个sqlSession的各种功能

public class mybatisutil {
    private static SqlSessionFactory sqlSessionFactory;//将原本的sqlSessionFactory提到这里,提升作用域
    static {
//        static初始的代码块,一开始就会加载
        InputStream inputStream = null;
        try {
            //获取sqlsession的对象,固定执行
            String resource = "mybatis-config.xml";
            inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();//这个工长就是生产各种的功能
    }
}


配置文件对应的就是dao的实现类,实现dao接口

<?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">
<mapper namespace="DAO.userDao">
<!--    相当于实现了接口 id就是函数的名字-->
    <select id="getUserList" resultType="pojo.User" >
-- 结果集不要写ListUserzheg ,直接写user就可以了
        select * from user_tb;
    </select>

</mapper>

测试

对于测试的程序要放到绿色的test里面
这里是userDAO的测试方法

public class userDaoTest {
    @Test
    public void test(){
        SqlSession sqlSession = mybatisutil.getSqlSession();
        //第一种方法直接getMapper 就是获取dao的实现,然后获取对象。
        userDao mapper = sqlSession.getMapper(DAO.userDao.class);
        List<User> userList = mapper.getUserList();
        for (User user : userList) {
            System.out.println(user);
        }
        sqlSession.close();
    }
}

Mybatis

注意!⚠️要提交事务才能使得结果发生改变,不然不会进入表里面

<select id="getUserList" resultType="pojo.User" >
-- 结果集不要写ListUserzheg ,直接写user就可以了
        select * from mybatis.user_tb;
    </select>
    <select id="getUserById" resultType="pojo.User" parameterType="int">
        select * from mybatis.user_tb where id = #{id};
    </select>
    <insert id="insertUser" parameterType="pojo.User">
        insert into mybatis.user_tb values (#{id},#{name},#{pwd});
    </insert>
<!--这里的上面的id name pwd就是User里面的属性,直接去取就是了-->
    <update id="updateUser" parameterType="pojo.User">
        update mybatis.user_tb
            set name = #{name},pwd=#{pwd}
        where id = #{id};
    </update>
    <delete id="deleteUser" parameterType="int">
        delete
        from mybatis.user_tb
        where id= #{id};
    </delete>
public List<User> getUserList();
    public User getUserById(int id);
    public void insertUser(User user);
    void updateUser(User user);
    void deleteUser(int i );

注意要提交事务

配置文件properties

数据库这些属性都是可外部配置且可动态替换的,既可以在典型的 Java 属性文件中配置,亦可通过 properties 元素的子元素来传递。具体的官方文档

我们来优化我们的配置文件

第一步 ; 在资源目录下新建一个db.properties
这里我的包错了因为这个转译符号&

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true
username=root
password=Mysql2486

第二步 : 将文件导入properties 配置文件

<configuration>
   <!--导入properties文件-->
   <properties resource="db.properties"/>

   <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>
   <mappers>
       <mapper resource="mapper/UserMapper.xml"/>
   </mappers>
</configuration>

配置文件优先级问题:优先外部文件
新特性:使用占位符

Mybatis注解模式

直接不用额外去实现,也不用谢标签了id和参数直接注解


@Select("select * from mybatis.user_tb")
    List<User> getAll();

Association-Collection-resultMap

下面有一个经典的错误:类没有加POJO所以找不到类

Caused by: org.apache.ibatis.exceptions.PersistenceException: 
### Error building SqlSession.
### The error may exist in studentMapper.xml
### The error occurred while processing mapper_resultMap[getAllMap]_association[teacher]
### Cause: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. The XML location is 'studentMapper.xml'. Cause: org.apache.ibatis.builder.BuilderException: Error resolving class. Cause: org.apache.ibatis.type.TypeException: Could not resolve type alias 'Teacher'.  Cause: java.lang.ClassNotFoundException: Cannot find class: Teacher

上面那个错误

association

一个学生只有一个老师

多个学生共有一个老师

<?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">
<mapper namespace="DAO.studentMapper">
    <select id="getAll" resultMap="getAllMap">
        SELECT s.id sid,s.name sname,t.name tname FROM mybatis.student s,mybatis.teacher t  WHERE s.tid=t.id;
    </select>
<!--    这下面的Type就是resultType的意思,例如说本来是要对应Student的返回值
        就是你要得到结果是Student的类,但因为有一个Teacher捣烂,所以
        我们用resultMap来接受,这个resultMap里面的type就定义为Student-->
    <resultMap id="getAllMap" type="pojo.Student">
        <result property="id" column="sid"/>
        <result property="name" column="sname"/>
        <association property="teacher" javaType="pojo.Teacher">
            <result property="name" column="tname"></result>
        </association>
    </resultMap>
</mapper>

collection

一个老师有多个学生 ,返回的使用collection来装

<?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">
<mapper namespace="DAO.teacherMapper">
    <select id="getById"  resultMap="getByIdMap">
        SELECT s.name sname,t.name tname FROM mybatis.student s,mybatis.teacher t  WHERE s.tid=t.id AND t.id=#{id};
    </select>
    <resultMap id="getByIdMap" type="pojo.Teacher">
        <result property="name" column="tname"/>
        <collection property="students" ofType="pojo.Student">
            <result property="name" column="sname"></result>
        </collection>
    </resultMap>
</mapper>
//在这个类teacher里面有一个students的成员,所以在resultMap里面使用collection 用ofType来制定返回的是什么
    private int id;
    private String name;
    private List<Student> students;

动态sql

IF语句

关键词:IF(test = "title!=null")

<?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">
<mapper namespace="DAO.blogMapper">
    <select id="queryOne" parameterType="map" resultType="pojo.Blog">
        select * from mybatis.blog where 1=1
        <if test="title!=null">
            and title = #{title}
        </if>
        <if test="author!=null">
            and author=#{author}
        </if>
    </select>

</mapper>

气死我了,这个map.put的位置放错了

加载完我才put

 SqlSession sqlSession = mybatisutil.getSqlSession();
        blogMapper mapper = sqlSession.getMapper(blogMapper.class);
        HashMap<String, String> map = new HashMap<>();
        map.put("title","帅气");
        List<Blog> blogs = mapper.queryOne(map);
        System.out.println("====/====///====");
        for (Blog blog : blogs) {
            System.out.println(blog);
        }

SQL片段-IF-WHEN -Otherwise 语句

IF语句

<update id="updateOne" parameterType="map">
        update mybatis.blog
        <set>
            <if test="title != null">
                title = #{title},
            </if>
            <if test="author != null">
                author = #{author},
            </if>
        </set>
        WHERE id = #{id}
    </update>

CHOOSE

<choose>
    <when test="title != null">
      AND title like #{title}
    </when>
    <when test="author != null and author.name != null">
      AND author_name like #{author.name}
    </when>
    <otherwise>
      AND featured = 1
    </otherwise>
  </choose>

缓存

如果不加CACHE的属性值,就需要将POJO的类Serialization一下,就是implments Serialization

序列化是深拷贝,所以反序列化后的对像和原对象不是同一个对象,故哈希值不同

报错的地方

posted @ 2022-08-28 11:29  Indullged  阅读(24)  评论(1编辑  收藏  举报