MyBatis-增刪改查

1.建立Maven項目,項目名稱mybatisdemo1,目錄結構如圖所示

wKiom1j0gDbyHyR6AAAsZRvqdQA512.png-wh_50


2.pom.xml中配置內容以下

<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.mycompany</groupId>
  <artifactId>mybatisdemo1</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <build/>
  
  <dependencies>
  	<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
	<dependency>
	    <groupId>org.apache.logging.log4j</groupId>
	    <artifactId>log4j-core</artifactId>
	    <version>2.7</version>
	</dependency>
	
	<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
	<dependency>
	    <groupId>org.mybatis</groupId>
	    <artifactId>mybatis</artifactId>
	    <version>3.4.1</version>
	</dependency>
	
	<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
	<dependency>
	    <groupId>mysql</groupId>
	    <artifactId>mysql-connector-java</artifactId>
	    <version>5.1.39</version>
	</dependency>
	
	<!-- https://mvnrepository.com/artifact/junit/junit -->
	<dependency>
	    <groupId>junit</groupId>
	    <artifactId>junit</artifactId>
	    <version>4.11</version>
	</dependency>
	
	
  </dependencies>
  
  
</project>


3.在src/main/java目錄建立實體類StudentBean,包名(com.mycompany.beans),目錄結構以下

wKiom1j0gMOAAhQBAABAvCYKboI283.png-wh_50


4.實體類StudentBean的內容以下

package com.mycompany.beans;

public class StudentBean {
	private Integer sid;
	private String name;
	
	public StudentBean() {
		super();
	}
	
	public StudentBean(String name) {
		super();
		this.name = name;
	}
	
	public StudentBean(Integer sid, String name) {
		super();
		this.sid = sid;
		this.name = name;
	}

	public Integer getSid() {
		return sid;
	}
	public void setSid(Integer sid) {
		this.sid = sid;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String toString() {
		return "StudentBean [sid="+sid+",name="+name+"]";
	}
}


5.在src/main/java下建立接口StudentMapper,包名(com.mycompany.mapper)目錄結構以下

wKiom1j0gS_AWSLKAABGqfA7sTU243.png-wh_50


6.接口StudentMapperr的內容以下

package com.mycompany.mapper;

import java.util.List;

import com.mycompany.beans.StudentBean;

public interface StudentMapper {
	/**
	 * 新增用戶
	 * @param student
	 * @return
	 * @throws Exception
	 */
	public int insertStudent(StudentBean student) throws Exception;
	
	/**
	 * 修改用戶
	 * @param student
	 * @param sid
	 * @return
	 * @throws Exception
	 */
	public int updateStudent(StudentBean student) throws Exception;
	
	/**
	 * 刪除用戶
	 * @return
	 * @throws Exception
	 */
	public int deleteStudent(int sid) throws Exception;
	
	/**
	 * 根據ID查詢學生信息
	 * @return
	 * @throws Exception
	 */
	public StudentBean selectStudentById(int sid) throws Exception;
	
	/**
	 * 查詢全部的學生信息
	 * @return
	 * @throws Exception
	 */
	public List<StudentBean> selectAllStudent() throws Exception;
}


7.在src/main/java下建立映射文件StudentMapper.xml,包名(com.mycompany.mapper),目錄結構以下

wKioL1j0gbLQrBfeAABHi8KfftI138.png-wh_50


8.映射文件StudentMapper.xml的內容以下

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mycompany.mapper.StudentMapper">
	<!--
		添加學生信息 
		在各類標籤中的id屬性必須和接口中的方法名相同 , id屬性值必須是惟一的,不可以重複使用。
		parameterType屬性指明查詢時使用的參數類型,resultType屬性指明查詢返回的結果集類型
	-->    
	<insert id="insertStudent" useGeneratedKeys="true" keyProperty="sid">
		INSERT INTO student (name) VALUES (#{name})
	</insert>
	
	<!-- 修改學生信息 -->
	<update id="updateStudent" parameterType="com.mycompany.beans.StudentBean">
		UPDATE student SET name = #{name} WHERE sid = #{sid}
	</update>
	
	<!-- 刪除學生信息 -->
	<delete id="deleteStudent" parameterType="int">
		DELETE FROM student WHERE sid=#{sid}
	</delete>
	
	<!-- 根據ID查詢學生信息 -->
	<select id="selectStudentById" parameterType="int" resultMap="studentMap">
		SELECT * FROM student WHERE sid=#{sid}
	</select>
	
	<!-- 查詢全部學生信息 -->
	<select id="selectAllStudent" resultMap="studentMap">
		SELECT * FROM student
	</select>
	
	<resultMap type="StudentBean" id="studentMap">
		<id property="sid" column="sid" javaType="java.lang.Integer"/>
		<result property="name" column="name" javaType="java.lang.String"/>
	</resultMap>
</mapper>


9.在src/main/java下建立工具類DBUtils,包名(com.mycompany.util)目錄結構以下

wKiom1j0gkHCSZILAABIAlUX2Mk591.png-wh_50


10.工具類DBUtils的內容以下

package com.mycompany.util;

import java.io.IOException;
import java.io.Reader;


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

public class DBUtils {
	public static SqlSessionFactory sessionFactory;
	
	static{
		try {
			Reader reader = Resources.getResourceAsReader("mybatis.cfg.xml");
			sessionFactory = new SqlSessionFactoryBuilder().build(reader);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static SqlSession getSession(){
		return sessionFactory.openSession();
	}
}


11.在src/main/resources下建立mysql.properties屬性文件,目錄結構以下

wKioL1j0gq7gjAPmAAA18NDVJ3k456.png-wh_50


12.mysql.properties屬性文件內容以下

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=


13.在src/main/resources下建立mybatis配置文件mybatis.cfg.xml,目錄結構以下

wKioL1j0gwrxh5YmAAA6F_O9DCA084.png-wh_50


14.配置文件mybatis.cfg.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="mysql.properties"></properties>
  	
  	<typeAliases>
  		<package name="com.mycompany.beans"/>
  	</typeAliases>
  	
  	<!-- 配置mybatis運行環境 -->
    <environments default="mybatis">
		<environment id="mybatis">
			<!-- type="JDBC" 表明使用JDBC的提交和回滾來管理事務 -->
            <transactionManager type="JDBC" />
            <!-- mybatis提供了3種數據源類型,分別是:POOLED,UNPOOLED,JNDI -->
            <!-- POOLED 表示支持JDBC數據源鏈接池 -->
            <!-- UNPOOLED 表示不支持數據源鏈接池 -->
            <!-- JNDI 表示支持外部數據源鏈接池 -->
            <dataSource type="POOLED">
            	<property name="driver" value="${jdbc.driver}" />
                <property name="url" value="${jdbc.url}" />
                <property name="username" value="${jdbc.username}" />
                <property name="password" value="${jdbc.password}" />
            </dataSource>
        </environment>
     </environments> 
     
     <mappers>
     	<package name="com/mycompany/mapper"/>
     </mappers>
     
</configuration>


15.在src/main/java下建立StudentService文件,包名(com.mycompany.service),目錄結構以下

wKioL1j0g3jzo5WQAAA8_AbjjzU856.png-wh_50


16.StudentService文件的內容以下

package com.mycompany.service;

import java.util.List;

import org.apache.ibatis.session.SqlSession;

import com.mycompany.beans.StudentBean;
import com.mycompany.mapper.StudentMapper;
import com.mycompany.util.DBUtils;

public class StudentService {
	/**
	 * 添加學生信息
	 * @param student
	 */
	public void insertStudent(StudentBean student){
		SqlSession session = DBUtils.getSession();
		StudentMapper mapper = session.getMapper(StudentMapper.class);
		try {
			int result = mapper.insertStudent(student);
			System.out.println(result);
			session.commit();
		} catch (Exception e) {
			e.printStackTrace();
			session.rollback();
		}
	}
	
	/**
	 * 修改學生信息
	 * @param student
	 */
	public void updateStudent(StudentBean student){
		SqlSession session = DBUtils.getSession();
		StudentMapper mapper = session.getMapper(StudentMapper.class);
		try {
			int result = mapper.updateStudent(student);
			System.out.println(result);
			session.commit();
		} catch (Exception e) {
			e.printStackTrace();
			session.rollback();
		}
	}
	
	/**
	 * 刪除學生信息
	 * @param sid
	 */
	public void deleteStudent(int sid){
		SqlSession session = DBUtils.getSession();
		StudentMapper mapper = session.getMapper(StudentMapper.class);
		try {
			int result = mapper.deleteStudent(sid);
			System.out.println(result);
			session.commit();
		} catch (Exception e) {
			e.printStackTrace();
			session.rollback();
		}
	}
	
	/**
	 * 根據ID查詢學生信息
	 * @param sid
	 */
	public void selectStudentById(int sid){
		SqlSession session = DBUtils.getSession();
		StudentMapper mapper = session.getMapper(StudentMapper.class);
		try {
			StudentBean student = mapper.selectStudentById(sid);
			System.out.println(student);
			session.commit();
		} catch (Exception e) {
			e.printStackTrace();
			session.rollback();
		}
	}
	
	/**
	 * 查詢全部學生信息
	 */
	public void selectAllStudent(){
		SqlSession session = DBUtils.getSession();
		StudentMapper mapper = session.getMapper(StudentMapper.class);
		try {
			List<StudentBean> students = mapper.selectAllStudent();
			for (StudentBean studentBean : students) {
				System.out.println(studentBean);
			}
			session.commit();
		} catch (Exception e) {
			e.printStackTrace();
			session.rollback();
		}
	}
}


17.在src/test/java下建立StudentServiceTest測試類,包名(com.mycompany.service)目錄結構以下

wKiom1j0g-jDXlwkAAA3ETKh-oQ097.png-wh_50


18.StudentServiceTest測試類的內容以下

package com.mycompany.service;

import org.junit.Test;

import com.mycompany.beans.StudentBean;

public class StudentServiceTest {

	/**
	 * 測試添加學生信息操做
	 */
	@Test
	public void insertStudentTest(){
		StudentService studentService = new StudentService();
		StudentBean student = new StudentBean("test insert");
		studentService.insertStudent(student);
	}
	
	/**
	 * 測試修改學生信息操做
	 */
	@Test
	public void updateStudent(){
		StudentService studentService = new StudentService();
		StudentBean studentBean = new StudentBean(5,"test update");
		studentService.updateStudent(studentBean);
	}
	
	/**
	 * 測試刪除學生信息操做
	 */
	@Test
	public void deleteStudent(){
		StudentService studentService = new StudentService();
		studentService.deleteStudent(7);
	}
	
	/**
	 * 測試根據ID查詢學生信息
	 */
	@Test
	public void selectStudentById(){
		StudentService studentService = new StudentService();
		studentService.selectStudentById(8);
	}
	
	/**
	 * 測試查詢全部學生信息
	 */
	@Test
	public void selectAllStudent(){
		StudentService studentService = new StudentService();
		studentService.selectAllStudent();
	}
}

wKioL1j0hByg-S04AABwCKMO5XE472.png-wh_50

相關文章
相關標籤/搜索