一个简单的mybatis运行项目——增删改查

项目结构图
各个文件在项目中的位置
使用Maven导入相关的包

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.example</groupId>
  <artifactId>Mybatis</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>
  <name>Mybatis Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.3</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.15</version>
    </dependency>
  </dependencies>
</project>

数据库表格

create table students(
  id  int(5) primary key,
  name varchar(10),
  sal double(8,2)
);

mybatis配置文件

<?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="mysql_developer">
        <!-- 连接环境信息,取一个任意唯一的名字 -->
        <environment id="mysql_developer">
            <!-- mybatis使用jdbc事务管理方式 -->
            <transactionManager type="jdbc"/>
            <!-- mybatis使用连接池方式来获取连接 -->
            <dataSource type="pooled">
                <!-- 配置与数据库交互的4个必要属性 -->
                <property name="driver" value="${mysql.driver}"/>
                <property name="url" value="${mysql.url}"/>
                <property name="username" value="${mysql.username}"/>
                <property name="password" value="${mysql.password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="studentMapper.xml"/>
    </mappers>
</configuration>

数据库配置信息

mysql.driver=com.mysql.cj.jdbc.Driver
mysql.url=jdbc:mysql://localhost:3306/zhi?characterEncoding=utf-8&serverTimezone=UTC&useSSL=true
mysql.username=root
mysql.password=123456

创建一个实体类Student

package main.com.zhiwenwu.entity;
public class Student {
    public Student(int id, String name, int sal) {
        this.id = id;
        this.name = name;
        this.sal = sal;
    }
    private int id;
    private String name;
    private int sal;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getSal() {
        return sal;
    }
    public void setSal(int sal) {
        this.sal = sal;
    }
}

实体与映射关系文件

<?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">

<!-- namespace属性是名称空间,必须唯一 -->
<mapper namespace="Student">

    <!-- resultMap标签:映射实体与表
         type属性:表示实体全路径名
         id属性:为实体与表的映射取一个任意的唯一的名字
    -->
    <resultMap type="main.com.zhiwenwu.entity.Student" id="studentMap"> <!-- type属性:表示实体全路径名 type="main.com.zhiwenwu.entity.Student" 一定要指向路径上的类,一开始是用type=“student”,加载失败-->
        <!-- id标签:映射主键属性
             result标签:映射非主键属性
             property属性:实体的属性名
             column属性:表的字段名
        -->
        <id property="id" column="id"/>
        <result property="name" column="name"/>
        <result property="sal" column="sal"/>
    </resultMap>
    <insert id="insert" parameterType="main.com.zhiwenwu.entity.Student" >
        INSERT INTO zhi.students (ID, NAME, SAL) VALUES (#{id},#{name},#{sal});
    </insert>

    <select id="findID" parameterType="int" resultType="main.com.zhiwenwu.entity.Student">
        SELECT * FROM STUDENTS WHERE id = #{id};
    </select>

    <select id="findAll" resultMap="studentMap">
		SELECT * FROM STUDENTS;
	</select>
    <delete id="deleteByID" parameterType="int">
        DELETE FROM STUDENTS where id = #{id};
    </delete>
    <update id="update" parameterType="main.com.zhiwenwu.entity.Student">
		update students set name=#{name},sal=#{sal} where id=#{id};
	</update>
</mapper>

DAO操作数据库

package main.com.zhiwenwu.dao;
import main.com.zhiwenwu.entity.Student;
import main.com.zhiwenwu.util.MybatisUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class StudentDao {

    public void add(Student student) throws Exception {
        //得到连接对象
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        try{
            //映射文件的命名空间.SQL片段的ID,就可以调用对应的映射文件中的SQL
            sqlSession.insert("Student.insert", student);
            sqlSession.commit();//提交才有事务
        }catch(Exception e){
            e.printStackTrace();
            sqlSession.rollback();
            throw e;
        }finally{
            MybatisUtil.closeSqlSession();
        }
    }
    public Student find(int id) throws Exception {
        //得到连接对象
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        try{
            //映射文件的命名空间.SQL片段的ID,就可以调用对应的映射文件中的SQL
            return sqlSession.selectOne("Student.findID", id);
        }catch(Exception e){
            e.printStackTrace();
            sqlSession.rollback();
            throw e;
        }finally{
            MybatisUtil.closeSqlSession();
        }
    }
    public List<Student> findAll() throws Exception{
        //得到连接对象
        SqlSession sqlsession = MybatisUtil.getSqlSession();
        return sqlsession.selectList("Student.findAll");
    }

    public void deleteByID(int id) throws Exception{
        //得到连接对象
        SqlSession sqlsession = MybatisUtil.getSqlSession();
        try {
            sqlsession.delete("Student.deleteByID",id);
            sqlsession.commit();
        }
        catch (Exception e){
            e.printStackTrace();
            sqlsession.rollback();
        }
    }

    //先取出对象,再修改,然后更新提交。
    public void update(Student student ) throws Exception {
        //得到连接对象
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        try{
            //映射文件的命名空间.SQL片段的ID,就可以调用对应的映射文件中的SQL
            sqlSession.update("Student.update", student);
            sqlSession.commit();
        }catch(Exception e){
            e.printStackTrace();
            sqlSession.rollback();
            throw e;
        }finally{
            MybatisUtil.closeSqlSession();
        }
    }

    public static void main(String[] args) throws Exception {
        StudentDao studentDao = new StudentDao();
        Student student = studentDao.find(2);
        student.setName("fucheng");
        student.setSal(2000);
        studentDao.update(student);
    }

}

mybatis简单增删改查

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值