Mybatis學習總結二之基於 XML 的單表CRUD操作

上一篇我們講了MyBatis配置文件中的配置及其優化:https://blog.csdn.net/qq_38720976/article/details/84484034

本文將通過項目使用MyBatis對錶執行CRUD操作

 mybatis-3.3.0.jar下載路徑:https://github.com/mybatis/mybatis-3/releases

1.主配置文件mybatis.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>    
     <environments default="development">
         <environment id="development">
             <transactionManager type="JDBC"/>
             <dataSource type="POOLED">
                 <property name="driver" value="com.mysql.jdbc.Driver" />
				<!-- 數據庫連接URL-->
				<property name="url" value="jdbc:mysql://localhost:3306/mysqljdbc?characterEncoding=utf-8" />
				<!-- 數據庫用戶名和密碼 -->
				<property name="username" value="root" />
				<property name="password" value="" />
             </dataSource>    
         </environment>
     </environments>
     
     <!-- 在配置文件中 關聯包下的實體類的映射文件-->
    <mappers>
        <mapper resource="com/aiit/dao/UserMapper.xml"/>
    </mappers>
</configuration>

2.實體映射文件配置UserMapper.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,namespace的值習慣上設置成包名+sql映射文件名,這樣就能夠保證namespace的值是唯一的
 例如namespace="me.gacl.mapping.userMapper"就是me.gacl.mapping(包名)+userMapper(userMapper.xml文件去除後綴)
  -->
<mapper namespace="com.aiit.dao.UserMapper">
    <!-- 在select標籤中編寫查詢的SQL語句, 設置select標籤的id屬性爲getUser,id屬性值必須是唯一的,不能夠重複
      使用parameterType屬性指明查詢時使用的參數類型,resultType屬性指明查詢返回的結果集類型
      resultType="com.aiit.pojo.User"就表示將查詢結果封裝成一個User類的對象返回
     User類就是users表所對應的實體類
     -->
	<select id="selectOne" parameterType="int" resultType="com.aiit.pojo.User">
		SELECT * FROM tbl_user WHERE tbl_user.id=#{id}
	</select>
	<select id="selectAll" resultType="com.aiit.pojo.User">
		SELECT * FROM tbl_user
	</select>
	<insert id="insertOne" parameterType="com.aiit.pojo.User"  >
		INSERT INTO tbl_user(tbl_user.name,tbl_user.age,tbl_user.address,tbl_user.birth) 
		VALUES(#{name},#{age},#{address},#{birth})
	</insert>
	<update id="updateOne" parameterType="com.aiit.pojo.User">
	update tbl_user set tbl_user.address = #{address} where id = #{id}
	</update>
	<delete id="deleteOne"  parameterType="com.aiit.pojo.User">
	delete from tbl_user where id = #{id}
	</delete>
	
</mapper>

3.User.java

package com.aiit.pojo;

import java.util.Date;

public class User {
  
private int id;
   private String name;
   private int age;
   private String address;
   private Date birth;
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 getAge() {
	return age;
}
public void setAge(int age) {
	this.age = age;
}
public String getAddress() {
	return address;
}
public void setAddress(String address) {
	this.address = address;
}
public Date getBirth() {
	return birth;
}
public void setBirth(Date birth) {
	this.birth = birth;
}
public User(int id, String name, int age) {
	super();
	this.id = id;
	this.name = name;
	this.age = age;
}
public User() {
	super();
}
public User(int id, String name, int age, String address, Date birth) {
	super();
	this.id = id;
	this.name = name;
	this.age = age;
	this.address = address;
	this.birth = birth;
}
public User(String name, int age, String address, Date birth) {
	super();
	this.name = name;
	this.age = age;
	this.address = address;
	this.birth = birth;
}
   
@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + ", age=" + age + ", address=" + address + ", birth=" + birth + "]";
	}
public User(String name, int age, String address) {
	super();
	this.name = name;
	this.age = age;
	this.address = address;
}
public User(int id, String address) {
	super();
	this.id = id;
	this.address = address;
}  

}

4.TestMyBatisDemo 測試類

package com.aiit.test;

import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.aiit.pojo.User;



public class TestMyBatisDemo {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		String resource="mybatis.cfg.xml";

		InputStream inputStream = TestMyBatisDemo.class.getClassLoader().getResourceAsStream(resource);

		SqlSessionFactory factory = new  SqlSessionFactoryBuilder().build(inputStream);
		SqlSession session = factory.openSession();

		//1.查詢
		String statement1 = "com.aiit.dao.UserMapper.selectOne";
		User user1 = session.selectOne(statement1,1);
		System.out.println("查詢結果: " + user1);


		//		2.添加
		//		String string = "2016-10-24";
		//		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		//		try {
		//			User user2 = new User("beifang", 15, "Chain",sdf.parse(string));
		//			String statement2 = "com.aiit.dao.UserMapper.insertOne";
		//			int insertResult= session.insert(statement2,user2);        
		//			System.out.println("插入成功"+insertResult);
		//		} catch (ParseException e) {
		//			// TODO Auto-generated catch block
		//			e.printStackTrace();
		//		}    

		//		3.修改
		//		String statement3 = "com.aiit.dao.UserMapper.updateOne";
		//		User user3 = new User(6, "中國");
		//		int updateResult = session.update(statement3, user3);
		//		System.out.println("修改成功"+updateResult);

		//4.刪除
		//String statement4 = "com.aiit.dao.UserMapper.deleteOne";
		//int deleteResult= session.delete(statement4, 2);
		//System.out.println("刪除成功"+deleteResult);

		//5.查詢所有
		String statement5 = "com.aiit.dao.UserMapper.selectAll";
		List<User> users = session.selectList(statement5);
		for(User user : users ) {
			System.out.println(user.getId()+" , "+user.getName()+" , "+user.getAge()+" , "+user.getAddress()+" , "+user.getBirth());
		}
		session.commit();
		session.close();
	}

}

測試效果控制檯輸出:

WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.apache.ibatis.reflection.Reflector (file:/D:/Users/Administrator/eclipse-workspace/Mybatis_frist/WebRoot/WEB-INF/lib/mybatis-3.2.7.jar) to method java.lang.Class.checkPackageAccess(java.lang.SecurityManager,java.lang.ClassLoader,boolean)
WARNING: Please consider reporting this to the maintainers of org.apache.ibatis.reflection.Reflector
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release

查詢結果: User [id=1, name=jim, age=19, address=USA, birth=Fri Dec 11 00:00:00 CST 1998]

插入成功1

修改成功1

刪除成功1

1 , jim , 19 , USA , Fri Dec 11 00:00:00 CST 1998
3 , 李雷 , 9 , China , Fri Dec 11 00:00:00 CST 2009
6 , beifang , 15 , 中國 , Mon Oct 24 00:00:00 CST 2016

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章