myBatis01

 

1.创建对应的数据库以及需要的表

myBatis01

2.创建对应的java项目,引入需要的mybatis需要的jar,以及连接mysql数据库的jar!

 myBatis01

3.创建对应的Student实体类

/**
 *学生的实体类
 */
public class Student {
    private Integer id; // 学生编号
    private String name; // 姓名
    private Integer age; // 年龄

    /**
     * 对应的有参无参构造以及对应的get和set方法
     */
    public Student() {
        super();
    }

    public Student(Integer id, String name, Integer age) {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

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

}

4.创建对应的接口以及mapper文件

public interface StudentDao {
    /**
     * 新增学生信息
     */
    void addStudent(Student student);
}
<?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="student">
    <insert id="addStudent" parameterType="cn.bdqn.bean.Student">
        insert into
        student(age,name) values(#{age},#{name})
    </insert>
</mapper>

5.创建对应的实现类和工具类

public class StudentDaoImpl implements StudentDao {

    //新增学生
    @Override
    public void addStudent(Student student) {
        SqlSession session=null;
        try {
            session = MyBatisUtils.getSession();  //获取session
            /**
             * 新增操作
             * addStudent:一定要和mapper文件中 的 id一致!
             */
            session.insert("addStudent", student);
            /**
             * 需要我们手动提交事务   02. 为什么 需要 手动提交
             * 03.在底层代码中查看得出结论
             *    底层的insert 以及delete 其实都是执行了 update操作
             *    关键点在于 dirty!!!
             * 04.怎么看到了session.commit  就是transaction.commit(); 
             *     001.MyBatisUtils 的方法 openSession的时候!默认没有传递参数==>autoCommit=false
             *         需要我们手动提交事务!
             *     002.session.insert() 底层默认调用了update()
             *          就是在update(),dirty=true!  数据是脏数据!
             *     003. session.commit(); 底层 默认    transaction.commit();
             *          之后dirty=false!  因为已经同步到数据库中!不是脏数据了!
             */
            session.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if (session!=null) {
                session.close();
            }
        }
        

    }

}
View Code

相关文章:

  • 2021-12-21
  • 2022-12-23
  • 2022-02-18
  • 2021-06-30
猜你喜欢
  • 2022-01-07
  • 2021-08-12
  • 2021-06-01
  • 2021-10-13
  • 2021-08-15
相关资源
相似解决方案