mybatis介紹、構架、實現增刪改查

目錄

原生態jdbc編程中的問題總結

jdbc編程步驟

jdbc問題總結如下

mybatis介紹

Mybatis架構

列:實現增刪改查

寫log4j.properties

mybatis的全局配置文件--sqlMapConfig.xml

創建po對象

sql映射文件---User.xml 

sql映射文件---Address.xml

測試文件Test.java

測試查詢

測試插入

測試刪除

測試更新

列2:使用動態代理的方式實現增刪改查

工具類Utils.java

mybatis的全局配置文件--sqlMapConfig.xml

創建po對象

創建接口--Mapper動態代理方式

測試:


 

原生態jdbc編程中的問題總結

jdbc編程步驟

  1. 加載數據庫驅動
  2. 創建並獲取數據庫鏈接
  3. 創建jdbc statement對象
  4. 設置sql語句
  5. 設置sql語句中的參數(使用preparedStatement)
  6. 通過statement執行sql並獲取結果
  7. 對sql執行結果進行解析處理
  8. 釋放資源(resultSet、preparedstatement、connection)
Public static void main(String[] args) {
			Connection connection = null;
			PreparedStatement preparedStatement = null;
			ResultSet resultSet = null;
			
			try {
				//加載數據庫驅動
				Class.forName("com.mysql.jdbc.Driver");
				
				//通過驅動管理類獲取數據庫鏈接
				connection =  DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8", "root", "mysql");
				//定義sql語句 ?表示佔位符
			String sql = "select * from user where username = ?";
				//獲取預處理statement
				preparedStatement = connection.prepareStatement(sql);
				//設置參數,第一個參數爲sql語句中參數的序號(從1開始),第二個參數爲設置的參數值
				preparedStatement.setString(1, "王五");
				//向數據庫發出sql執行查詢,查詢出結果集
				resultSet =  preparedStatement.executeQuery();
				//遍歷查詢結果集
				while(resultSet.next()){
					System.out.println(resultSet.getString("id")+"  "+resultSet.getString("username"));
				}
			} catch (Exception e) {
				e.printStackTrace();
			}finally{
				//釋放資源
				if(resultSet!=null){
					try {
						resultSet.close();
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				if(preparedStatement!=null){
					try {
						preparedStatement.close();
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				if(connection!=null){
					try {
						connection.close();
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}

			}

		}

jdbc問題總結如下

  1. 數據庫鏈接創建、釋放頻繁造成系統資源浪費從而影響系統性能,如果使用數據庫鏈接池可解決此問題。
  2. Sql語句在代碼中硬編碼,造成代碼不易維護,實際應用sql變化的可能較大,sql變動需要改變java代碼。
  3. 使用preparedStatement向佔有位符號傳參數存在硬編碼,系統不易維護
  4. 對結果集解析存在硬編碼(查詢列名),sql變化導致解析代碼變化,系統不易維護,如果能將數據庫記錄封裝成pojo對象解析比較方便。

mybatis介紹

MyBatis 本是apache的一個開源項目iBatis, 2010年這個項目由apache software foundation 遷移到了google code,並且改名爲MyBatis,實質上Mybatis對ibatis進行一些改進。

MyBatis是一個優秀的持久層框架,它對jdbc的操作數據庫的過程進行封裝,使開發者只需要關注 SQL 本身,而不需要花費精力去處理例如註冊驅動、創建connection、創建statement、手動設置參數、結果集檢索等jdbc繁雜的過程代碼

Mybatis通過xml或註解的方式將要執行的各種statement(statement、preparedStatemnt、CallableStatement)配置起來,並通過java對象和statement中的sql進行映射生成最終執行的sql語句,最後由mybatis框架執行sql並將結果映射成java對象並返回。

 

Mybatis架構

  • sqlMapConfig.xml,此文件作爲mybatis的全局配置文件
  • mapper.xml文件即sql映射文件
  • 通過mybatis環境等配置信息構造SqlSessionFactory即會話工廠
  • 由會話工廠創建sqlSession即會話
  • mybatis底層自定義了Executor執行器接口操作數據庫,Executor接口有兩個實現,一個是基本執行器、一個是緩存執行器。Mapped Statement也是mybatis一個底層封裝對象,它包裝了mybatis配置信息及sql映射信息等
  • Mapped Statement對sql執行輸出結果進行定義,包括HashMap、基本類型、pojo,Executor通過Mapped Statement在執行sql後將輸出結果映射至java對象中,輸出結果映射過程相當於jdbc編程中對結果的解析處理過程

列:實現增刪改查

寫log4j.properties

# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

mybatis的全局配置文件--sqlMapConfig.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" />
				<property name="url" value="jdbc:mysql://localhost:3306/1107mybatis" />
				<property name="username" value="root" />
				<property name="password" value="123" />
			</dataSource>
		</environment>
	</environments>
	<!-- 加載sql語句映射文件 -->
	<mappers>
		<mapper resource="com/lsw/demo/User.xml"/>
		<mapper resource="com/lsw/demo/Address.xml"/>
	</mappers>
</configuration>

創建po對象

sql映射文件---User.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">

<!-- sql語句映射文件 -->

<mapper namespace="com.lsw.demo"><!-- 命名空間 -->
	<!-- 1查詢1條記錄 value可以隨便寫 Preparing: select * from user where id=? --><!--sqlstatment語句 -->
	<select id="queryAll" parameterType="int" resultType="com.lsw.demo.User">
		select * from user where id=#{value}
	</select>
	<!-- 1.1查詢1條記錄 Preparing: select * from user where id=1 -->
	<select id="queryAllOne" parameterType="int" resultType="com.lsw.demo.User">
		select * from user where id=${value}
	</select>
    <!-- 1.2查詢--拼串 -->
    <select id="selectByUserName" parameterType="java.lang.String" resultType="com.lsw.demo.User">
	   select  * from user where userName like  '%${value}%'
	</select>
	<!-- 2添加 添加不需要返回值******************************* -->
	<insert id="insertUser" parameterType="com.lsw.demo.User">
		insert into user (id,userName,password,age)		values(#{id},#{userName},#{password},#{age})
	</insert>
	<!-- 3刪除****************************** -->
	<delete id="delOne" parameterType="int">
	   delete from user where id=#{id}
	</delete>
	<!--4 更新*******************************  -->
	<update id="updateOne" parameterType="com.lsw.demo.User" >
	  update user set userName=#{userName},password=#{password},age=#{age} where id=#{id}
	</update>
	<!-- 5自增主鍵  before:之前***********************-->
	<insert id="insertForId" parameterType="com.lsw.demo.User">
	  <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
	     select last_insert_id()
	  </selectKey>
	  insert into user(userName,password,age) values (#{userName},#{password},#{age})
	</insert>

</mapper>

sql映射文件---Address.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="com.lsw.demo">
    <!-- 6 插入數據--主鍵是uuid -->
	 <insert id="insertAddress" parameterType="com.lsw.demo.Address">
	     <selectKey resultType="java.lang.String" keyProperty="id" order="BEFORE">
	         SELECT uuid();
	     </selectKey>
	     insert into address(id,address,email) values(#{id},#{address},#{email});
	 </insert>
</mapper>

測試文件Test.java

測試查詢

    /**
     * 1查詢1條語句
     * @throws Exception
     */
	@org.junit.Test
	public void queryAll() throws Exception {

		    // 1獲取配置文件
			InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
			// 2創建SqlSessionFactory工廠類
			SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
			// 3 獲取qlSession
			SqlSession sqlSession = sqlSessionFactory.openSession();
			// 4查詢語句
			User user = sqlSession.selectOne("com.lsw.demo.queryAll", 1);
			System.out.println(user);
	}
    /**
     * 1.1查詢1條語句
     * @throws Exception
     */
	@org.junit.Test
	public void queryAllOne() throws Exception {

		    // 1獲取配置文件
			InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
			// 2創建SqlSessionFactory工廠類
			SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
			// 3 獲取qlSession
			SqlSession sqlSession = sqlSessionFactory.openSession();
			// 4查詢語句
			User user = sqlSession.selectOne("com.lsw.demo.queryAllOne", 1);
			System.out.println(user);
	}
    /**
     * 1.2查詢-拼串
     * @throws Exception
     */
	@org.junit.Test
	public void selectByUserName() throws Exception {

		    // 1獲取配置文件
			InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
			// 2創建SqlSessionFactory工廠類
			SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
			// 3 獲取qlSession
			SqlSession sqlSession = sqlSessionFactory.openSession();
			// 4查詢語句
			List<User> user = sqlSession.selectList("com.lsw.demo.selectByUserName", "lao");
			System.out.println(user);
	}

測試插入

    /**
     * 2插入1條數據
     * @throws Exception
     */
	@org.junit.Test
	public void insertUser() throws Exception {
		System.out.println(1111);

		    // 1獲取配置文件
			InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
			// 2創建SqlSessionFactory工廠類
			SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
			// 3 獲取qlSession
			SqlSession sqlSession = sqlSessionFactory.openSession();
			// 4插入數據
			User user=new User(100, "laosun", "11", 11);
			int a = sqlSession.insert("com.lsw.demo.insertUser", user);
			System.out.println(a);
			 sqlSession.commit(); //5事務提交
	}

主鍵自增方式插入

    /**
     * 5插入數據----主鍵自增的方式-
     * @throws Exception
     */
	@org.junit.Test
	public void insertForId() throws Exception {
		System.out.println(1111);

		    // 1獲取配置文件
			InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
			// 2創建SqlSessionFactory工廠類
			SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
			// 3 獲取qlSession
			SqlSession sqlSession = sqlSessionFactory.openSession();
			// 4數據操作 
			User user=new User("laosun","fendou",27);
			int a = sqlSession.insert("com.lsw.demo.insertForId", user);
			System.out.println(a);
			sqlSession.commit(); //5事務提交
			
	}

插入---主鍵是uuid

	/**
     *6插入數據----主鍵是uuid
     * @throws Exception
     */
	@org.junit.Test
	public void insertAddress() throws Exception {
		System.out.println(1111);

		    // 1獲取配置文件
			InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
			// 2創建SqlSessionFactory工廠類
			SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
			// 3 獲取qlSession
			SqlSession sqlSession = sqlSessionFactory.openSession();
			// 4數據操作 刪除
			Address ads=new Address("beijing","beijing111");
			int a = sqlSession.insert("com.lsw.demo.insertAddress", ads);
			System.out.println(a);
			sqlSession.commit(); //5事務提交
			
	}

測試刪除

    /**
     * 3刪除1條數據
     * @throws Exception
     */
	@org.junit.Test
	public void delOne() throws Exception {
		System.out.println(1111);

		    // 1獲取配置文件
			InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
			// 2創建SqlSessionFactory工廠類
			SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
			// 3 獲取qlSession
			SqlSession sqlSession = sqlSessionFactory.openSession();
			// 4數據操作 刪除
			
			int a = sqlSession.insert("com.lsw.demo.delOne", 3);
			System.out.println(a);
			sqlSession.commit(); //5事務提交
			
	}

測試更新

    /**
     * 4更新1條數據
     * @throws Exception
     */
	@org.junit.Test
	public void updateOne() throws Exception {
		System.out.println(1111);

		    // 1獲取配置文件
			InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
			// 2創建SqlSessionFactory工廠類
			SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
			// 3 獲取qlSession
			SqlSession sqlSession = sqlSessionFactory.openSession();
			// 4數據操作 刪除
			User user=new User(7,"laosun","fendou",27);
			int a = sqlSession.insert("com.lsw.demo.updateOne", user);
			System.out.println(a);
			sqlSession.commit(); //5事務提交
			
	}

 

列2:使用動態代理的方式實現增刪改查

工具類Utils.java

com.demo.tools

public class Utils {
	private static SqlSessionFactory sqlSessionFactory;

	public static SqlSessionFactory getSqlSessionFactory() throws Exception {
		// 1獲取全局配置文件
		InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
		// 2創建SqlSessionFactory工廠類
		sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		return sqlSessionFactory;
	}
}

mybatis的全局配置文件--sqlMapConfig.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"></properties><!-- 讀取屬性文件 -->

	<typeAliases>
		<!-- 單個別名 -->
		<!-- <typeAlias type="com.iotek.po.Goods" alias="goods"/> -->
		<!--批量別名:掃描整個包下的類,類的別名就是類名(首字母大寫或者小寫都可以) -->
		<package name="com.demo.po" />
		<package name="com.demo2.po" />
		
	</typeAliases>
	<environments default="development">
		<environment id="development">
			<transactionManager type="JDBC" />
			<!-- 配置數據源 -->
			<dataSource type="POOLED">
				<property name="driver" value="${driver}" />
				<property name="url" value="${url}" />
				<property name="username" value="${username}" />
				<property name="password" value="${password}" />
			</dataSource>
		</environment>
	</environments>
	<!-- 加載sql語句映射文件 -->
	<mappers>
		<mapper resource="com/demo2/po/Student.xml" />
	</mappers>
</configuration>

創建po對象

創建接口--Mapper動態代理方式

public interface StudentDao {
 public Student queryById(int id);//查詢
 public int addStudent(Student student);//增加
 public int updateStudent(@Param("aa")Student student);//修改
 public int delStudent(@Param("bb") Student student);//刪除
}

 

<?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="com.demo2.dao.StudentDao">
	<select id="queryById" parameterType="int" resultType="Student">
       select * from student where id=#{id} 
	</select>
	<insert id="addStudent" parameterType="Student">
	  insert into student (sname,sage,saddress,sphone) values(#{sname},#{sage},#{saddress},#{sphone})
	</insert>
	<update id="updateStudent" parameterType="Student" >
	  update student set sname=#{aa.sname},sage=#{aa.sage},saddress=#{aa.saddress},sphone=#{aa.sphone} where id=#{aa.id}
	</update>
	<delete id="delStudent" parameterType="Student">
	 delete from student where id=#{bb.id}
	</delete>
</mapper>

測試:

public class Test2Demo {
	/**
	 * 1通過id查詢
	 * @throws Exception
	 */
	@Test
	public void qqueryById() throws Exception {
		SqlSession sqlSession = Utils.getSqlSessionFactory().openSession();
		StudentDao studentDao = sqlSession.getMapper(StudentDao.class);// Mapper動態代理(接口代理對象)
		Student student = studentDao.queryById(2);
		System.out.println(student);
	}
	/**
	 * 2添加
	 * @throws Exception
	 */
	@Test
	public void addStudent() throws Exception {
		SqlSession sqlSession = Utils.getSqlSessionFactory().openSession();
		StudentDao studentDao = sqlSession.getMapper(StudentDao.class);// Mapper動態代理(接口代理對象)
		Student student=new Student("小飛", 19, "北京八大胡同", 1920287934);
		int aa = studentDao.addStudent(student);
		System.out.println(aa);
	}	
	/**
	 * 3更新
	 * @throws Exception
	 */
	@Test
	public void updateStudent() throws Exception {
		SqlSession sqlSession = Utils.getSqlSessionFactory().openSession();
		StudentDao studentDao = sqlSession.getMapper(StudentDao.class);// Mapper動態代理(接口代理對象)
		Student student=new Student(6, "大飛", 20, "上海", 19374375);
		System.out.println(student.getId());
		int aaa = studentDao.updateStudent(student);
		System.out.println(aaa);
	}	
	/**
	 * 4刪除
	 * @throws Exception
	 */
	@Test
	public void delStudent() throws Exception {
		SqlSession sqlSession = Utils.getSqlSessionFactory().openSession();
		StudentDao studentDao = sqlSession.getMapper(StudentDao.class);// Mapper動態代理(接口代理對象)
		Student student=new Student();
		student.setId(7);
		int s = studentDao.delStudent(student);
		System.out.println(s);
	}
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

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