Mybatis基于XML与基于注解实现CRUD

数据库

实体类Student

package com.pojo;

/**
 * Description :
 * Created by Resumebb
 * Date :2021/3/26
 */
public class Student {
    /**
     * 和数据库中的STudent表对应
     */
    private Integer SID;
    private String Sname;
    private String Ssex;
    private Integer Sage;
    //省略的getter和setter方法

    public Integer getSID() {
        return SID;
    }

    public void setSID(Integer SID) {
        this.SID = SID;
    }

    public String getSname() {
        return Sname;
    }

    public void setSname(String sname) {
        Sname = sname;
    }

    public String getSsex() {
        return Ssex;
    }

    public void setSsex(String ssex) {
        Ssex = ssex;
    }

    public Integer getSage() {
        return Sage;
    }

    public void setSage(Integer sage) {
        Sage = sage;
    }

    @Override
    public String toString() {
        return "com.pojo{" +
                "SID=" + SID +
                ", Sname='" + Sname + '\'' +
                ", Ssex='" + Ssex + '\'' +
                ", Sage=" + Sage +
                '}';
    }
}

StudentMapper接口定义

package com.mapper;

import com.pojo.Student;

/**
 * Description :
 * Created by Resumebb
 * Date :2021/3/26
 */

public interface StudentMapper {
    public Student selectStudentById(Integer id);
    public int deleteStudentById(Integer id);
    public int addStudent(Student student);
    public int updateStudent(Student student);
}

StudentMapper.xml映射文件中的CRUD操作标签配置

<?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,命令空间:保证命名空间唯一,一般是对应的mapper.java的包全路径-->
<mapper namespace="com.mapper.StudentMapper">
    <select id="selectStudentById" parameterType="int" resultType="POJOStudent" >
        select * from Student where SID = #{id}
    </select>
<!--    删除SQL-->
    <delete id="deleteStudentById" parameterType="int" >
        delete from Student where SID = #{id}
    </delete>
<!--添加SQL-->
    <insert id="addStudent" parameterType="POJOStudent" useGeneratedKeys="false">
        insert into student (Sid,Sname,Ssex,Sage) values (#{id},#{name},#{sex},#{age})
    </insert>
<!--修改SQL-->
    <update id="updateStudent" parameterType="POJOStudent">
        update student set Sname = #{Sname}, Ssex=#{Ssex}, Sage=#{Sage} where SID = #{SID}
    </update>
</mapper>

查询实现

    //查询操作
    public static void select(){
        String resources = "mybatis-config.xml";
        try {
            InputStream resourceAsStream = Resources.getResourceAsStream(resources);
            //创建会话工厂
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
            //获取对话
            SqlSession sqlSession = sqlSessionFactory.openSession();
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
            Student student = studentMapper.selectStudentById(2);
            System.out.println(student);
            sqlSession.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

采用日志进行打印,日志依赖:

    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.12</version>
    </dependency>

日志配置log4j.properties: 

## debug 级别
log4j.rootLogger=DEBUG,Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
log4j.appender.Console.layout = org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d{yyyy-MM-dd-HH\:mm\:ss,SSS} [%t]  [%c] [%p] - %m%n
log4j.logger.com.tulun=DEBUG  /


##输出sql 语句
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG</strong>

 效果:

删除实现

    public static void delete(){
        String resources = "mybatis-config.xml";
        try {
            InputStream resourceAsStream = Resources.getResourceAsStream(resources);
            //创建会话工厂
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
            //获取对话
            SqlSession sqlSession = sqlSessionFactory.openSession();
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
            studentMapper.deleteStudentById(5);
            sqlSession.commit();
            sqlSession.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

效果:

数据库中id为5的学生信息已经删除。 

插入实现

    public static void add(){
        String resources = "mybatis-config.xml";
        try {
            InputStream resourceAsStream = Resources.getResourceAsStream(resources);
            //创建会话工厂
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
            //获取对话
            SqlSession sqlSession = sqlSessionFactory.openSession();
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
            Student student = new Student();
            student.setSID(6);
            student.setSname("韩磊");
            student.setSsex("男");
            student.setSage(40);
            studentMapper.addStudent(student);
            sqlSession.commit();
            sqlSession.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

数据库中新数据插入成功 

修改实现

    public static void update(){
        String resources = "mybatis-config.xml";
        try {
            InputStream resourceAsStream = Resources.getResourceAsStream(resources);
            //创建会话工厂
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
            //获取对话
            SqlSession sqlSession = sqlSessionFactory.openSession();
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
            Student student = new Student();
            student.setSID(4);
            student.setSname("李星");
            student.setSsex("男");
            student.setSage(40);
            studentMapper.updateStudent(student);
            sqlSession.commit();
            sqlSession.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

数据库中: 

 

resultMap与findAll

将resultType类型改成resultMap进行测试。

对于二者的区别:

MyBatis中在查询进行select映射的时候,返回类型可以用resultType,也可以用resultMap,resultType是直接表示返回类型的,而resultMap则是对外部ResultMap的引用,但是resultType跟resultMap不能同时存在。在MyBatis进行查询映射时,其实查询出来的每一个属性都是放在一个对应的Map里面的,其中键是属性名,值则是其对应的值。

①当提供的返回类型属性是resultType时,MyBatis会将Map里面的键值对取出赋给resultType所指定的对象对应的属性。所以其实MyBatis的每一个查询映射的返回类型都是ResultMap,只是当提供的返回类型属性是resultType的时候,MyBatis对自动的给把对应的值赋给resultType所指定对象的属性。

②当提供的返回类型是resultMap时,因为Map不能很好表示领域模型,就需要自己再进一步的把它转化为对应的对象,这常常在复杂查询中很有作用。

在StudentMapper.xml中配置resultMap与findAll方法

    <resultMap id="studentResult" type="POJOStudent">
<!--        id/result: 标签属性的介绍
            property: (必须)指定java类中的属性名
            column: (必须)指定数据库列明
            javaType:(可省略)指定java属性类型
            typeHandler:(可省略)指定类型转换器
-->
        <result column="SID" property="SID"></result>
        <result column="Sname" property="Sname"></result>
        <result column="Ssex" property="Ssex"></result>
        <result column="Sage" property="Sage"></result>
    </resultMap>
    <select id="findAll" resultMap="studentResult">
        select * from student;
    </select>
    public void findAll(){
        String resources = "mybatis-config.xml";
        try {
            InputStream resourceAsStream = Resources.getResourceAsStream(resources);
            //创建会话工厂
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
            //获取对话
            SqlSession sqlSession = sqlSessionFactory.openSession();
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
            List<Student> students = studentMapper.findAll();
            for (Student s:students) {
                System.out.println(s);
            }
            sqlSession.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

 

测试结果:

 

基于注解方式

UserMapper

package com.mapper;

import com.pojo.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;

/**
 * Description :
 * Created by Resumebb
 * Date :2021/3/29
 */
public interface UserMapper {


    @Results(
            id = "userResult",
            value = {
                    @Result(column = "id", property = "id"),
                    @Result(column = "name", property = "name"),
                    @Result(column = "password", property = "password")
            }
    )

    @Select("select * from user where id = #{id}")
    public User selectUserById(Integer id);

    @Insert("insert into user (name,password) values (#{name}, #{password})")
    public int addUser(User user);
}

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">
<!--mapper根标签 namespace,命令空间:保证命名空间唯一,一般是对应的mapper.java的包全路径-->
<mapper namespace="com.mapper.UserMapper">

</mapper>

使用Junit测试 

package com.mapper;

import com.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.io.InputStream;

import static org.junit.jupiter.api.Assertions.*;

/**
 * Description :
 * Created by Resumebb
 * Date :2021/3/29
 */
class UserMapperTest {
    SqlSessionFactory sqlSessionFactory;
    @BeforeEach
    public void before(){
        String resources = "mybatis-config.xml";
        try {
            InputStream resourceAsStream = Resources.getResourceAsStream(resources);
            //创建会话工厂
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        } catch (Exception e) {
        }
    }
    @Test
    void selectUserById() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.selectUserById(1);
        System.out.println(user);
    }

    @Test
    void addUser() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = new User();
        user.setName("zhangsan");
        user.setPassword("abcd");
        int res = mapper.addUser(user);
        sqlSession.commit();
        System.out.println(res);
    }
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值