Mybatis不使用Mapper接口——————對數據庫中的表進行增刪改查

數據庫

員工表:employee

int       varchar     int      date               decimal

 

項目目錄結構

1.實體類

package com.ujiuye.bean;


import lombok.*;

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

@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@ToString
public class Employee {
    private int id;
    private String name;
    private int age;
    private Date birthday;
    private BigDecimal salary;
}

2.在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.ujiuye</groupId>
    <artifactId>mybatis001</artifactId>
    <version>1.0.0</version>
    <dependencies>

        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
        </dependency>

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

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

    </dependencies>

</project>

3.Mybatis核心配置文件mybatis-config.xml

mappers標籤關聯映射文件,resource從classes文件夾中尋找映射文件

4.EmployeeMapper.xml映射文件

不使用Mapper接口時,<mapper namespace=”">中的namespace可以隨意賦值,但如果使用Mapper接口,後續會介紹如何賦值

<!--values後面只傳入參數即可,錯誤寫法name=#{name}-->

id相當於jdbc中的statement,每一個id執行一條sql語句,在同一個Mapper.xml文件中是唯一的 

parameterType:傳入的參數類型,如果是實體類,是包名+類名

resultType:返回類型,需要注意的是,查詢一條和查詢全部在Mapper.xml文件中都是寫實體類的類型,查詢全部不寫List類型
    <insert id="insertEmployee" parameterType="com.ujiuye.bean.Employee">
        insert into employee(name,age,birthday,salary) values(#{name},#{age},#{birthday},#{salary})                                                     </insert>

<?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">
    <!--from一定不要寫成form-->
    <select id="findById" parameterType="int" resultType="com.ujiuye.bean.Employee">
        select id,name,age,birthday,salary from employee where id = #{id}
    </select>
    <!--values後面只傳入參數即可,錯誤寫法name=#{name}-->
    <insert id="insertEmployee" parameterType="com.ujiuye.bean.Employee">
        insert into employee(name,age,birthday,salary) values(#{name},#{age},#{birthday},#{salary})
   </insert>
    
    <delete id="deleteById" parameterType="int">
        delete from employee where id=#{id}
    </delete>
    
    <select id="findAll" resultType="com.ujiuye.bean.Employee">
        select id,name,age,birthday,salary from employee
    </select>
    
    <update id="updateEmployee" parameterType="com.ujiuye.bean.Employee">
        update employee set name=#{name},age=#{age},birthday=#{birthday},salary=#{salary} where id=#{id}
    </update>
</mapper>

 

5.獲取sqlSession工具類,日期和字符串互相轉換的工具類

package com.ujiuye.utils;

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 java.io.IOException;
import java.io.InputStream;

public class MybatisUtil {
    //需要將sqlSessionFactory設置爲靜態的,否則靜態代碼塊中和獲取sqlSession中的方法不能引用
    private static  SqlSessionFactory sqlSessionFactory = null;

    //靜態代碼塊,只加載一次
    static {
        String resource = "mybatis-config.xml";
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream(resource);
        } catch (IOException e) {
            e.printStackTrace();
        }
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    }

    //一定記得加上static修飾,否則其他靜態方法中不可以調用
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }
}
package com.ujiuye.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateUtil {
	
	public static Date stringToDate(String str){
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		
		Date date = null;
		try {
			date = sdf.parse(str);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		return date;
	}
	
	public static String dateToString(Date date){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		return sdf.format(date);
	}

}

 

6.測試類

需要注意的是,增刪改必須提交事務!!!

package com.ujiuye.test;


import com.ujiuye.bean.Employee;
import com.ujiuye.utils.DateUtil;
import com.ujiuye.utils.MybatisUtil;
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.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class MybatisTest {

    @Test
    public void testFindById() throws Exception{
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        Employee employee = sqlSession.selectOne("test.findById", 1);
        System.out.println(employee);
    }


    @Test
    public void testInsertEmployee() throws Exception{
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();

        Employee employee = new Employee();

        employee.setName("CC");

        employee.setAge(18);

        employee.setBirthday(DateUtil.stringToDate("1996-3-3"));

        employee.setSalary(new BigDecimal(6666.6));

        sqlSession.insert("test.insertEmployee",employee);
        sqlSession.commit();
        sqlSession.close();
    }

    @Test
    public void testDeleteEmployee() throws Exception{
       SqlSession sqlSession = MybatisUtil.getSqlSession();
       sqlSession.delete("test.deleteById",8);
       //增刪改一定要記得提交事務
       sqlSession.commit();
       sqlSession.close();
    }

    @Test
    public void testFindAll() throws Exception{
        SqlSession sqlSession = MybatisUtil.getSqlSession();

        List<Employee> list = new ArrayList<Employee>();
        list = sqlSession.selectList("test.findAll");

        for(Employee employee : list){
            System.out.println(employee);
        }
    }


    @Test
    public void testUpdate()throws Exception{
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        Employee employee = sqlSession.selectOne("test.findById", 14);
        employee.setAge(55);

        sqlSession.update("updateEmployee",employee);
        sqlSession.commit();
        sqlSession.close();
    }
}

 

 

發佈了156 篇原創文章 · 獲贊 13 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章