Mybatis入门案例-----使用IDEA 创建 maven java 项目,通过mapper映射文件实现增删改查(内含源码及详细解释)

题目

使用IDEA 创建 MAVEN  JAVA 项目

根据下图 在mysql数据库中创建员工表(t_employee)

创建实体类 Employee  并创建mapper映射文件(使用mybatis中的mapper映射文件)

以及测试类 对创建的mapper映射文件进行增删改查以及测试

项目目录结构

1.在数据库中创建表T_Employee(大小写无所谓)

DROP TABLE IF EXISTS t_employee;
CREATE TABLE t_employee (
  id int(11) NOT NULL AUTO_INCREMENT,
  name varchar(30) DEFAULT NULL,
  age int(11) DEFAULT NULL,
  birthday date DEFAULT NULL,
  salary decimal(10,0) DEFAULT NULL,
  PRIMARY KEY (id)
)

2.创建实体类Employee

package com.xiongluoluo.bean;

import lombok.*;

import java.math.BigDecimal;
import java.util.Date;

/**
 * Created by Administrator on 2019/12/21 0021.
 */
@Getter
@Setter
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class Employee {
    private int id;
    private String name;
    private int age;
    private Date birthday;
    private BigDecimal salary;
}

2.要使用mybatis的mapper映射文件,就必须先导入mybatis依赖,由于要和数据库进行交互,所以还要导入mysql连接数据库也就是JDBC的依赖.

2.1   pom.xml文件

<?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>com.xiongluoluo</groupId>
    <artifactId>mybatis1</artifactId>
    <version>1.0.0</version>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.8</version>
            <scope>provided</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <!--JDBC的依赖(https://mvnrepository.com中搜索mysql,点击第一个即可)-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
        </dependency>

    </dependencies>

</project>

 

2.2 mybatis-config.xml文件

<?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"/>
    <typeAliases>
        <package name="com.xiongluoluo.bean"/>
    </typeAliases>
    <environments default="mysql">
        <environment id="mysql">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driverClassName}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="com/xiongluoluo/mapper/EmployeeMapper.xml"/>
    </mappers>
</configuration>

 

2.3 EmployeeMapper.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="test">
    <resultMap id="employeeResultMap" type="Employee">
        <id property="id" column="id"/>
        <result property="name" column="name"/>
        <result property="age" column="age"/>
        <result property="birthday" column="birthday"/>
        <result property="salary" column="salary"/>
    </resultMap>

    <select id="selectAllEmployee" resultMap="employeeResultMap">
      /*查询全部*/
        select id,name,age,birthday,salary from t_employee
    </select>
    
    <select id="selectEmployeeById" resultMap="employeeResultMap">
       /* 根据id查询Employee*/
       select id,name,age,birthday,salary from t_employee where id = #{id}
    </select>

    <insert id="insertEmployee" parameterType="Employee">
         /*添加员工*/
         insert into t_employee values(null,#{name},#{age},#{birthday},#{salary})
    </insert>
    
    <delete id="deleteEmployee" parameterType="int">
        /*根据id删除员工*/
        delete from t_employee where id = #{id}
    </delete>
    
    <update id="updateEmployee" parameterType="Employee">
         /*更新员工信息*/
        update t_employee set name = #{name},age=#{age},birthday=#{birthday},salary=#{salary} where id=#{id}
    </update>

</mapper>

 

2.4 db.properties文件

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql:///test2
username=root
password=1234

 

 

4 测试类

package com.xiongluoluo.test;

import com.xiongluoluo.bean.Employee;
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.Test;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2019/12/21 0021.
 */
public class MybatisTest {
    //查询全部
    @Test
    public void testSelectAllEmployee(){
        String resource = "mybatis-config.xml";
        try {
            InputStream is = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            SqlSession sqlSession = sqlSessionFactory.openSession();
            List<Employee> list = sqlSession.selectList("selectAllEmployee");
            for(Employee employee : list){
                System.out.println(employee);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //通过id查询Employee
    @Test
    public void testSelectEmployeeById(){
        String resource = "mybatis-config.xml";
        try {
            InputStream is = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            SqlSession sqlSession = sqlSessionFactory.openSession();
            Employee employee = sqlSession.selectOne("test.selectEmployeeById",7);
            //namespace+id,参数
            System.out.println(employee);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //添加员工
    @Test
    public void testInsertEmployee(){
        String resource = "mybatis-config.xml";
        try {
            InputStream is = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            SqlSession sqlSession = sqlSessionFactory.openSession();
            Employee employee = new Employee();
            employee.setName("熊落落");
            employee.setAge(26);
            employee.setBirthday(new Date());
            employee.setSalary(new BigDecimal(5000));
            int result = sqlSession.insert("test.insertEmployee", employee);
            sqlSession.commit();
            if(result>0){
                System.out.println("插入成功!");
            }else{
                System.out.println("插入失败!");
            }
            sqlSession.commit();
            sqlSession.close();
            //增删改的时候一定要记得提交事务,不然数据库是不会更新的,这个跟之前不太一样,切记切记

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //删除员工
    @Test
    public void testDeleteEmployee(){
        String resource = "mybatis-config.xml";
        try {
            InputStream is = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            SqlSession sqlSession = sqlSessionFactory.openSession();
            int result = sqlSession.delete("test.deleteEmployee",20);
            if(result>0){
                System.out.println("删除成功!");
            }else{
                System.out.println("删除失败!");
            }
            sqlSession.commit();
            sqlSession.close();
            //提交事务,提交事务,提交事务!!!!

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //更新员工信息
    @Test
    public void testUpdateEmployee(){
        String resource = "mybatis-config.xml";
        try {
            InputStream is = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            SqlSession sqlSession = sqlSessionFactory.openSession();
            Employee employee = sqlSession.selectOne("test.selectEmployeeById", 7);
            int result = sqlSession.update("test.updateEmployee", employee);
            if(result>0){
                System.out.println("更新成功!");
            }else{
                System.out.println("更新失败!");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 

注释1:由于想多熟悉一下生成SqlSession那部分的代码,所以测试类的时候没有封装工具类.

注释2:有一个点需要注意,就是增删改的时候一定要提交事务,查询可以不提交,增删改一定不能忘,不然数据库中的值是不会改变的.

发布了100 篇原创文章 · 获赞 7 · 访问量 7577

猜你喜欢

转载自blog.csdn.net/qq_40245464/article/details/103653746