MyBatis基於xml檔案的 CURD案例

大大頭梨發表於2020-10-19

提示:文章寫完後,目錄可以自動生成,如何生成可參考右邊的幫助文件

一、整體的專案結構

1.展開(整體是一個很簡單的專案結構,多餘的東西跟此案例無關的我打上了馬賽克)

1.src下的conf.xml檔案
2.com.beans 實體類包
3.com.mapping 對映檔案包
4.com.mybatis.utils 工具包
5.com.test 測試包

以及專案下lib資料夾(放jar包用的)

在這裡插入圖片描述

二、詳細程式碼

1.src下的conf.xml檔案

conf.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>
	<settings>  
	     <!-- 開啟log4j的標籤-->
       <setting name="logImpl" value="STDOUT_LOGGING" />  
  </settings>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <!-- 配置資料庫連線資訊 -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://localhost:3306/wy" />
                <property name="username" value="root" />
                <property name="password" value="root" />
            </dataSource>
        </environment>
    </environments>
	
	<mappers>
        <!-- 註冊userMapper.xml檔案,
        userMapper.xml位於me.gacl.mapping這個包下,所以resource寫成me/gacl/mapping/userMapper.xml-->
        <mapper resource="com/mapping/studentMapper.xml"/>
    </mappers>
    
   
   

</configuration>

2.com.beans 實體類包

Student實體類

package com.beans;

import java.io.Serializable;
import java.util.List;

public class Student implements Serializable{
	private Integer id;
	private String name;
	private Integer age;
	private String gender;
	
	
	
	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;
	}
	public String getGender() {
		return gender;
	}
	public void setGender(String gender) {
		this.gender = gender;
	}
	
	@Override
	public String toString() {
		return "Student [id=" + id + ", name=" + name + ", age=" + age + ", gender=" + gender
				+ "]";
	}
	
	
	
	
}

3.com.mapping 對映檔案包

studentMapper.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">

		<!-- namespace自定義的姓名空間,一般以路徑加上檔名命名 -->
<mapper namespace="com.mapping.studentMapper">
			<!-- id是自定義的名字,相當於方法名     parameterType方法傳參的型別    -->
	<insert id="insertStudent" parameterType="com.beans.Student">
		INSERT INTO student (NAME,age,gender) value(#{name},#{age},#{gender})
	</insert>
	
	<delete id="deleteStudent" parameterType="int">
		DELETE FROM student where id=#{id}
	</delete>
	
	<update id="updateStudent" parameterType="com.beans.Student">
		UPDATE  student set name=#{name},age=#{age},gender=#{gender} WHERE id=#{id}
	</update>
	
	<!-- 根據id查詢使用者  resultType返回值的型別-->
	<select id="selectStudent" parameterType="int" resultType="com.beans.Student">
		select * from student where id=#{id}
	</select>
	
	<!-- 查詢所有使用者 -->
	<select id="getAllStudent" resultType="com.beans.Student">
		select * from student
	</select>
	
	

    
</mapper>

4.com.mybatis.utils 工具包

MybatisUtils.java

package com.mybatis.utils;

import java.io.InputStream;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;


public class MybatisUtils {
	public static SqlSession getSqlSession(Boolean b) {
		//mybatis的配置檔案
        String resource ="conf.xml";
        //使用類載入器載入mybatis的配置檔案(它也載入關聯的對映檔案)
        InputStream is =  MybatisUtils.class.getClassLoader().getResourceAsStream(resource);
        //構建sqlSession的工廠
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
        
        SqlSession session = null;
        if(b) {
        	 session = sessionFactory.openSession(true);
        }
        
		return session;
		
	}
	
	public static SqlSession getSqlSession() {
		//mybatis的配置檔案
        String resource ="conf.xml";
        //使用類載入器載入mybatis的配置檔案(它也載入關聯的對映檔案)
        InputStream is =  MybatisUtils.class.getClassLoader().getResourceAsStream(resource);
        //構建sqlSession的工廠
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
        
        SqlSession session = sessionFactory.openSession();
        
        
		return session;
		
	}
}

5.com.test 測試包

test.java

package com.test;

import java.util.List;

import org.apache.ibatis.session.SqlSession;

import com.beans.Student;
import com.beans.Teacher;
import com.mybatis.utils.MybatisUtils;

public class test {
	public static void main(String[] args) {
		SqlSession s=MybatisUtils.getSqlSession(true);
		// s.insert
		 // s.delete
		 //  s.update
		 //  s.selectOne
		  // s.selectList
	//五個基本方法測試就行了
	}
}

相關文章