第二章 Mybatis的基础操作(增删改查)

2.1 查询数据
2.2.1查询单条数据

新建实体类:

@Data
public class Student {
    private Long id;
    private String name;
    private Integer age;
}

映射文件:
Student.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">
<mapper namespace="com.mybatis.dmomain.Student">
 
    <select id="selectone" resultType="com.mybatis.dmomain.Student">
     SELECT  id,name,age FROM  student WHERE  id=#{id}
    </select>
</mapper>

全局配置文件:

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

查询方法:
//查询单条数据

@Test
void selectOne() {
    InputStream inputStream = null;
    try {
        //1.获取去全局配置文件
        inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        //2.加载全局配置文件
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
        //3.创建SqlSession对象,传递true表示自动提交事务
        SqlSession session = factory.openSession(true);
        //4.执行查询方法
        //参数1:映射文件中namespace标签名称+id名称
        //参数2:需要传递的参数
        Student student = session.selectOne("com.mybatis.dmomain.Student.selectone", 1L);
        //5.关闭资源
        session.close();
        System.out.println(student);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

2.2.2查询多条数据

   @Test
    void selectAll() {
        InputStream inputStream = null;
        try {
            //1.获取去全局配置文件
            inputStream = Resources.getResourceAsStream("mybatis-config.xml");
            //2.加载全局配置文件
            SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
            //3.创建SqlSession对象,传递true表示自动提交事务
            SqlSession session = factory.openSession(true);
            //4.执行查询方法
            //参数1:映射文件中namespace标签名称+id名称
            List<Student> students = session.selectList("com.mybatis.dmomain.Student.selectAll");
            //5.关闭资源
            session.close();
            for (Student s : students) {
                System.out.println(s);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

映射文件改动内容:

 <select id="selectAll" resultType="com.mybatis.dmomain.Student">
     SELECT  id,name,age FROM  student
 </select>

在这里插入图片描述
补充:
1.返回一个map:

@Test
void geMap() {
    SqlSession session = MyBatisUtil.getSession();
    StudentMapper mapper = session.getMapper(StudentMapper.class);
    Map map = mapper.getMap(2L);
    System.out.println(map);
    session.close();
}
  <select id="getMap" resultType="map">
        SELECT  * FROM student WHERE id=#{id}
    </select>

map 的key就是列名,value就是值。
2.将某个字段作为key,整个对象作为value:

@Test
void getMap() {
    SqlSession session = MyBatisUtil.getSession();
    StudentMapper mapper = session.getMapper(StudentMapper.class);
    Map map = mapper.getMap();
    System.out.println(map);
    session.close();
}
//返回的id作为key,Student就是一个对象
@MapKey("id")
Map<Integer , Student> getMap();

此处用了一个注解。
在这里插入图片描述

2.2 更新数据

  @Test
    void update() {
        InputStream inputStream = null;
        try {
            //1.获取去全局配置文件
            inputStream = Resources.getResourceAsStream("mybatis-config.xml");
            //2.加载全局配置文件
            SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
            //3.创建SqlSession对象,传递true表示自动提交事务
            SqlSession session = factory.openSession(true);
            //4.执行查询方法
            //参数1:映射文件中namespace标签名称+id名称
            //参数2:需要传递的参数
            Student student = new Student();
            student.setId(1L);
            student.setName("陆小凤");
            student.setAge(22);
            session.update("com.mybatis.dmomain.Student.update", student);
            //5.关闭资源
            session.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

映射文件:

 <update id="update">
      UPDATE  student SET  name=#{name},age=#{age} WHERE id=#{id}
    </update>

在这里插入图片描述
2.3删除数据

 @Test
    void delete() {
        InputStream inputStream = null;
        try {
            //1.获取去全局配置文件
            inputStream = Resources.getResourceAsStream("mybatis-config.xml");
            //2.加载全局配置文件
            SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
            //3.创建SqlSession对象,传递true表示自动提交事务
            SqlSession session = factory.openSession(true);
            //4.执行查询方法
            //参数1:映射文件中namespace标签名称+id名称
            //参数2:需要传递的参数
            session.delete("com.mybatis.dmomain.Student.delete", 1L);
            //5.关闭资源
            session.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

xml映射文件:

 <update id="delete">
       DELETE  FROM  student WHERE id=#{id}
    </update>

2.4增加数据
2.4.1:增加一条数据

@Test
void insert() {
    InputStream inputStream = null;
    try {
        //1.获取去全局配置文件
        inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        //2.加载全局配置文件
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
        //3.创建SqlSession对象,传递true表示自动提交事务
        SqlSession session = factory.openSession(true);
        //4.执行查询方法
        //参数1:映射文件中namespace标签名称+id名称
        //参数2:需要传递的参数
        Student student = new Student();
        student.setName("西门吹雪");
        student.setAge(18);
        session.insert("com.mybatis.dmomain.Student.insert", student);
        //5.关闭资源
        session.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
XML映射文件:
<insert id="insert">
       INSERT INTO  student (name,age) VALUES  (#{name},#{age})
    </insert>

在这里插入图片描述
2.4.2保存数据返回主键值
在实际的开发中,会有这样的需求,再保存一条数据之后,需要返回保存该条数据的主键,用于下面操作。举个例子:
你去一个网站注册信息,一般有个快速注册按钮,注册完毕之后会让你继续完善个人信息,此时就需要前一个页面注册时候生成的主键,此处作为条件更新数据(新注册相当于插入数据,完善信息相当于更新数据)。

useGeneratedKeys:表示设置为自动生成主键
keyProperty:表示生成的主键映射到你的哪一个字段属性上
<insert id="insert" useGeneratedKeys="true" keyProperty="id">
   INSERT INTO  student (name,age) VALUES  (#{name},#{age})
</insert>

在这里插入图片描述
在这里插入图片描述
本章小结
在本小节中,主要演示使用Mybatis进行基础的增删改查操作,其实没有什么难度,就是一一些基础的SQL语句的书写。
再者就是调用Mybatis中几个方法。此处再来分析下:
查询数据调用的是:
查询单个数据:
selectOne(String url ,Objec object),返回一个查询的实体对象,参数1是namespace+id名称,参数2就是你传递的条件。
查询多个数据:
selectList(String url),返回一个List集合,参数1就是namespace+id,
然后在映射文件中进行编写SQL语句即可

<select  id=" "  >
  SQL  语句
  </selerct>

其实也并不一定需要这么写,最后绝对执行的结果是里面的SQL语句,但是这个就是规范好一点,这么用就可以了。
更新数据:
update(String url,Object object),参数1依然是namespace+id,参数2则传递一个需要被更新的对象即可。
删除数据:
delete(String url,Object object),参数1依然是namespace+id,参数2则传递一个需要被删除的对象id即可。
增加一条数据:
insert(String url,Object object)参数1依然是namespace+id,参数2则传递一个需要增加数据的对象id即可。
最后还讲解一个了在增加的时候可以获取返回自动增长的主键:

 <insert id="insert" useGeneratedKeys="true" keyProperty="id">

这个以后也比较常用,就是配置两个属性,分别是开启和映射到对象的哪个属性上。
关于还有一个#{属性名}和代码重复的问题,再下一个章节将会对这个进行讲解。

猜你喜欢

转载自blog.csdn.net/weixin_43686925/article/details/85477150