Mybatis1.0——框架入門,從0到簡單增刪改查資料

海棠花開發表於2018-11-01

JavaWeb框架學習文章
首先是準備Mybatis的jar包
Mybatis下載地址
1,匯入Mybatis-x.x.x.jar和lib中的依賴包
2,匯入要使用的資料庫的驅動包
3,建立一個config檔案,在config資料夾下建立一個log4j.properties
開啟mybatis自帶的pdf,翻到logging配置中找需要的配置資訊,大概如下
配置log4j.properties
這裡貼出mybatis-3.4.6中的資訊

# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.org.mybatis.example.BlogMapper=TRACE
# 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

由於我們在開發階段,所以上述內容中的ERROR也就是日誌級別,建議改成DEBUG,投入工作後可以用INFO,ERROR
4,在config下建立一個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">
			<!-- 使用jdbc事務管理 -->
			<transactionManager type="JDBC"/>
			<!-- 配置資料庫連線池 -->
			<dataSource type="POOLED">
				<property name="driver" value="com.mysql.jdbc.Driver"/>
				<property name="url" value="jdbc:mysql://localhost:3306/test"/>
				<property name="username" value="root"/>
				<property name="password" value="123456"/>
			</dataSource>					
		</environment>
	</environments>
	
	<!-- 載入對映檔案 -->
	<mappers>
		<mapper resource="sqlmap/user.xml"/>
	</mappers>
	
</configuration>

5,在config中建立一個sqlmap包,然後包內建立一個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">

<!-- namespace名稱空間:對sql進行分類化管理,隔離sql -->
<mapper namespace="test">
		<!-- 用來查詢 
				id:用來標識這條select
				parameterType:傳入的引數型別
				resultType:返回的sql對映成的java物件型別
				
				#{}表示一個佔位符
				#{}中如果要輸入的引數名是簡單型別,那麼引數名可以任意:如#{id},#{value}
				${}表示將接收到的引數不加任何修飾拼接到sql中
				${value},如果接受的型別是簡單型別,引數只能填value
				${}的方式 可能引起sql注入,不推薦使用
		-->
		<select id="findUserById" parameterType="int" resultType="com.hhh.dao.User">
			select * from user where id = #{id}
		</select>
		
		<select id="findUserByName" parameterType="java.lang.String" resultType="com.hhh.dao.User">
			select * from user where name like '%${value}%'
		</select>
</mapper>

6,在src包下建立常見的User物件,該物件對應資料庫中的表,user.xml中的返回型別也就是它
7,建立測試類(主要測試的是單項結果查詢,和多項結果查詢)

package com.hhh.test;

import java.io.InputStream;
import java.util.List;
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 com.hhh.dao.User;

public class MyTest {
	@Test
	public void test1() throws Exception {
		//讀取mybatis配置檔案
		InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");//由於建立的是原始碼包,所以可以直接讀
		
		//建立會話工廠,傳入配置資訊
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
		
		//通過工廠得到SqlSession
		SqlSession sqlSession = sqlSessionFactory.openSession();
	
		/*
		 * 通過SqlSession運算元據庫
		 * 引數1:名稱空間和sql的id
		 * 引數2: 傳向佔位符的值
		 * */
		User user = sqlSession.selectOne("test.findUserById",1);
		System.out.println(user);
		
		List<User> selectList = sqlSession.selectList("test.findUserByName","張三");
		System.out.println(selectList);
		sqlSession.close();
	}
}


執行結果:

DEBUG [main] - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - Opening JDBC Connection
DEBUG [main] - Created connection 422392391.
DEBUG [main] - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@192d3247]
DEBUG [main] - ==>  Preparing: select * from user where id = ? 
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - <==      Total: 1
User [id=1, name=張三1, age=20, tel=12341]
DEBUG [main] - ==>  Preparing: select * from user where name like '%張三%' 
DEBUG [main] - ==> Parameters: 
DEBUG [main] - <==      Total: 2
[User [id=1, name=張三1, age=20, tel=12341], User [id=2, name=張三2, age=21, tel=12342]]

插入資料:
修改user.xml

		<!-- 
			向user表中插入資訊
			由於id自增所以不需要填
		 -->
		<insert id="insertInfoToUser" parameterType="com.hhh.dao.User">
			insert into user(name, age, tel) values(#{name},#{age},#{tel})
		</insert>

測試類:

		User user = new User("王五3",18,"12346");
		sqlSession.insert("test.insertInfoToUser", user);
		sqlSession.commit();//如果不提交將會回滾事務

執行結果:

DEBUG [main] - Opening JDBC Connection
DEBUG [main] - Created connection 1181869371.
DEBUG [main] - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@4671e53b]
DEBUG [main] - ==>  Preparing: insert into user(name, age, tel) values(?,?,?) 
DEBUG [main] - ==> Parameters: 王五3(String), 18(Integer), 12346(String)
DEBUG [main] - <==    Updates: 1
DEBUG [main] - Committing JDBC Connection [com.mysql.jdbc.JDBC4Connection@4671e53b]

獲取自增長的id值:
修改user.xml

		<insert id="insertInfoToUser" parameterType="com.hhh.dao.User">
			insert into user(name, age, tel) values(#{name},#{age},#{tel})
			<!-- keyProperty:引數名
				 order:插入後獲取
				 resultType:返回值型別
			 -->
			<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
				select last_insert_id();
			</selectKey>
		</insert>

修改測試類:

		User user = new User("王五3",18,"12346");
		sqlSession.insert("test.insertInfoToUser", user);
		sqlSession.commit();//如果不提交將會回滾事務
		System.out.println(user.getId());

結果:

DEBUG [main] - ==>  Preparing: insert into user(name, age, tel) values(?,?,?) 
DEBUG [main] - ==> Parameters: 王五3(String), 18(Integer), 12346(String)
DEBUG [main] - <==    Updates: 1
DEBUG [main] - ==>  Preparing: select last_insert_id(); 
DEBUG [main] - ==> Parameters: 
DEBUG [main] - <==      Total: 1
DEBUG [main] - Committing JDBC Connection [com.mysql.jdbc.JDBC4Connection@6950e31]
9

刪除使用者:
修改user.xml

		<delete id="deleteById" parameterType="java.lang.Integer">
			delete from user where id = #{id}
		</delete>

測試類:

		sqlSession.delete("deleteById", 6);
		sqlSession.commit();

修改使用者:
修改user.xml

		<update id="updateUser" parameterType="com.hhh.dao.User">
			update user set name = #{name} where id = #{id}
		</update>

需要注意的是這裡的引數不是簡單型別,所以不能夠隨便填,欄位名和屬性名需要對應。由於根據id修改資料,所以這裡傳入的屬性必須要有id值。

		User user = new User("王五3",18,"12346");
		user.setId(5);
		sqlSession.update("updateUser", user);
		sqlSession.commit();

相關文章