mybatis学习笔记

发布时间 2023-03-29 10:39:48作者: xiaoxing~

1、第一个mybatis

导入依赖

//mysql依赖
<dependency> <groupId>com.mysql</groupId> <artifactId>mysql-connector-j</artifactId> <version>8.0.31</version> </dependency>
//mybatis依赖
<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis</artifactId>
  <version>3.5.11</version>
</dependency>

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "https://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/db_stu?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
<!--映射xml,可映射多个文件--> <mappers> <mapper resource="com/xx/dao/userMapper.xml"/> </mappers> </configuration>

 

创建工具类

 private static SqlSessionFactory sqlSessionFactory;
    static {
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    public static SqlSession getSqlSession()
    {
         return  sqlSessionFactory.openSession();
    }

创建实体类

private int id;
    private String StudentName;
    private String gender;
    private int age;

    public Student() {
    }

    public Student(int id, String studentName, String gender, int age) {
        this.id = id;
        StudentName = studentName;
        this.gender = gender;
        this.age = age;
    }

    public int getId() {
        return id;
    }

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

    public String getStudentName() {
        return StudentName;
    }

    public void setStudentName(String studentName) {
        StudentName = studentName;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", StudentName='" + StudentName + '\'' +
                ", gender='" + gender + '\'' +
                ", age=" + age +
                '}';
    }

创建接口

package com.xx.dao;
import com.xx.pojo.Student;
import java.util.List;

public interface studentMapper {
//查询全部学生
List<Student> getAllStudents();
//根据学号查找学生
Student getStudentById(int id);
//添加学生
int addStudent(Student stu);
//修改信息
int updateStudent(Student stu);
//删除学生信息
int deleteStudent(int id);
}

实现

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xx.dao.studentMapper">
<select id="getAllStudents" resultType="com.xx.pojo.Student" >
select * from db_stu.student
</select>
<select id="getStudentById" resultType="com.xx.pojo.Student" parameterType="int">
select * from db_stu.student where id =#{id}
</select>
<insert id="addStudent" parameterType="com.xx.pojo.Student">
insert into db_stu.student(id,StudentName,gender,age) values(#{id},#{StudentName},#{gender},#{age})
</insert>
<update id="updateStudent" parameterType="com.xx.pojo.Student">
update db_stu.student set StudentName=#{StudentName},gender=#{gender},age=#{age} where id=#{id};
</update>
<delete id="deleteStudent" parameterType="int">
delete from db_stu.student where id =#{id};
</delete>
</mapper>

测试实例

@Test
public void addStudent()
{
SqlSession sqlSession=mybatisUtil.getSqlSession();
studentMapper stuMapper=sqlSession.getMapper(studentMapper.class);
int res= stuMapper.addStudent(new Student(6,"无敌战胜","神",999));
if(res>0)
{
System.out.println("插入成功");
sqlSession.commit();
}
sqlSession.close();
}
@Test
public void queryAllStudents()
{
SqlSession sqlSession=mybatisUtil.getSqlSession();
studentMapper stuMapper=sqlSession.getMapper(studentMapper.class);
List<Student> students=stuMapper.getAllStudents();
for (Student student : students) {
System.out.println(student);
}
sqlSession.close();
}
@Test
public void queryStudent()
{
SqlSession sqlSession=mybatisUtil.getSqlSession();
studentMapper stuMapper=sqlSession.getMapper(studentMapper.class);
Student stu=stuMapper.getStudentById(2);
System.out.println(stu);
sqlSession.close();
}
@Test
public void updateStudnet()
{
SqlSession sqlSession=mybatisUtil.getSqlSession();
studentMapper mapper = sqlSession.getMapper(studentMapper.class);
int res=mapper.updateStudent(new Student(6,"xxxiaoxing","男",19));
if(res>0)
{
System.out.println("修改成功");
sqlSession.commit();
}
sqlSession.close();
}
@Test
public void deleteStudent()
{
SqlSession sqlSession=mybatisUtil.getSqlSession();
studentMapper mapper = sqlSession.getMapper(studentMapper.class);
int res=mapper.deleteStudent(6);
if(res>0)
{
System.out.println("删除成功");
sqlSession.commit();
}
sqlSession.close();
}

注意:增删改需提交事务(SqlSession.commit())//否则操作无效

maven资源过滤问题 

在pom.xml添加

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