Mybatis-詳解1

1mybatis概述

2mybatisHello 示例程序

3、傳統方式mybatis的增,刪,改,查實現

4Mapper接口方式的mybatis的增,刪,改,查實現

5mybatis的核心配置之properties

6mybatis的核心配置之settings

7mybatis的核心配置之typeAliases

8、mybatis的核心配置之environments

9、mybatis的核心配置之databaseIdProvider

10mybatis的核心配置之Mapper


1mybatis概述

1.1mybatis簡介

MyBatis 是支持定製化 SQL、存儲過程以及高級映射的優秀的持久層框架。

 

MyBatis 避免了幾乎所有的 JDBC 代碼和手動設置參數以及獲取結果集。

 

MyBatis可以使用簡單的XML或註解用於配置和原始映射,將接口和JavaPOJOPlain Old Java Objects,普通的Java對象)映射成數據庫中的記錄.

 

 

1.2mybatis歷史

原是apache的一個開源項目iBatis, 20106月這個項目由apache software foundation 遷移到了google code,隨着開發團隊轉投Google Code旗下,ibatis3.x正式更名爲Mybatis ,代碼於201311月遷移到Github(下載地址見後)。

iBATIS一詞來源於“internet”和“abatis”的組合,是一個基於Java的持久層框架。iBATIS提供的持久層框架包括SQL MapsData Access ObjectsDAO

 

 

1.3、爲什麼要使用mybatis

MyBatis是一個半自動化的持久化層框架。

 

jdbc編程---當我們使用jdbc持久化的時候,sql語句被硬編碼到java代碼中。這樣耦合度太高。代碼不易於維護。在實際項目開發中會經常添加sql或者修改sql,這樣我們就只能到java代碼中去修改。

 

HibernateJPA

長難複雜的SQL,對於Hibernate而言處理也不容易

內部自動生產的SQL,不容易做特殊優化。

基於全映射的全自動框架javaBean存在大量字段時無法只映射部分字段。導致數據庫性能下降。

 

對開發人員而言,核心sql還是需要自己優化

sqljava編碼分開,功能邊界清晰,一個專注業務、一個專注數據。

可以使用簡單的XML或註解用於配置和原始映射,將接口和JavaPOJO映射成數據庫中的記錄。成爲業務代碼+底層數據庫的媒介

 

 

2mybatisHello 示例程序

2.1、創建一個數據庫和一個單表


drop database if exists mybatis;

create database mybatis;

use mybatis;
##############################################################################
################################### 單表 ######################################
##############################################################################
## 創建單表
create table t_user(
	`id` int primary key auto_increment,
	`last_name`	varchar(50),
	`sex` int
);

insert into t_user(`last_name`,`sex`) values('mxx',1);

select * from t_user;

2.2、搭建mybatis開發環境

需要導入jar包:

log4j-1.2.17.jar

mybatis-3.4.1.jar

mysql-connector-java-5.1.7-bin.jar

 

添加配置文件:

mybatis-config.xml

 

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

2.3、創建Pojo對象User

public class User {

	private int id;
	private String lastName;
	private int sex;

2.4、在src目錄創建mybatis-config.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 數據源
					POOLED	表示使用數據庫連接池
			 -->
			<dataSource type="POOLED">
				<property name="driver" value="com.mysql.jdbc.Driver" />
				<property name="url" value="jdbc:mysql://localhost:3306/mybatis" />
				<property name="username" value="root" />
				<property name="password" value="root" />
			</dataSource>
		</environment>
	</environments>
	<!-- 引入sql語句對應的配置文件 -->
	<mappers>
		<mapper resource="com/tcent/pojo/UserMapper.xml" />
	</mappers>
</configuration>

2.5、創建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">
<!-- 
	namespace 屬性一般情況下。
		一種定義規則:
			一種是使用對應的javaBean的全類名
			一種是使用Mapper接口的全類名
 -->
<mapper namespace="com.tcent.pojo.User">
	<!-- 
		select 定義select查詢語句
			id			給你要定義的sql語句,設置一個唯一的id值。
			resultType	查詢完返回的類型
			#{id}		這是一個佔位符
	 -->
	<select id="selectUserById" resultType="com.tcent.pojo.User">
		select id,last_name lastName,sex from t_user where id = #{id}
	</select>
</mapper>

2.6、傳統mybatishello world 示例代碼

@Test
	public void testQueryUserById() throws IOException {
		// 讀取mybatis的核心配置文件
		InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
		// 通過SqlSessionFactoryBuilder創建一個SqlSessionFactory實例(只有一個實例)
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
		is.close();
		// session相當於Connection對象
		SqlSession session = sqlSessionFactory.openSession();
		try {
			// selectOne 執行select查詢語句,返回一個對象
			// sql語句是由 namespance+"."+select標籤的id值
			User user = session.selectOne("com.tcent.pojo.User.selectUserById", 1);
			
			System.out.println( user );
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
	}

mapper.xml中和核心配置文件中mybatis-config.xmlAlt+/會沒有提示,只需要按照如下的方式,將鼠標放在對應的xml頁面,並windowpreferences,找到對應的文件dtd,導進去就可以了(mybatis-3-config.dtd,mybatis-3-mapper.dtd),下面給出文件,配置mybatis配置文件的提示:


3、傳統方式mybatis的增,刪,改,查實現

 

3.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">
<!-- 
	namespace 屬性一般情況下。
		一種定義規則:
			一種是使用對應的javaBean的全類名
			一種是使用Mapper接口的全類名
 -->
<mapper namespace="com.tcent.pojo.User">

	<!-- 
		select 定義select查詢語句
			id			給你要定義的sql語句,設置一個唯一的id值。
			resultType	查詢完返回的類型
			#{id}		這是一個佔位符
	 -->
	<select id="selectUserById" resultType="com.tcent.pojo.User">
		select id,last_name lastName,sex from t_user where id = #{id}
	</select>
	
	<!-- 
			id		定義一個唯一標識
			resultType	定義查詢返回的類型
	 -->
	<select id="queryUsers" resultType="com.tcent.pojo.User">
		select id,last_name lastName,sex from t_user
	</select>
	
	<!-- 
		delete標籤定義delete語句
		parameterType		設置參數的類型(可選)	
	 -->
	<delete id="deleteUserById" parameterType="int">
		delete from t_user where id = #{id}	
	</delete>
	
	<!-- 
		update標籤定義一個update語句
	 -->
	<update id="updateUser" parameterType="com.tcent.pojo.User">
		update t_user set last_name = #{lastName},sex = #{sex} where id = #{id}
	</update>
	
	<!-- 
		insert標籤定義insert語句
	 -->
	<insert id="saveUser" parameterType="com.tcent.pojo.User">
		insert into t_user(`last_name`,`sex`) values(#{lastName},#{sex})
	</insert>
	
</mapper>

3.2.1、保存用戶

@Override
	public int saveUser(User user) {
		SqlSession session = sqlSessionFactory.openSession();
		try {
			// 執行插入
			int result = session.insert("com.tcent.pojo.User.saveUser", user);
			session.commit();
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
		return 0;
	}

<!-- 
		insert標籤定義insert語句
	 -->
	<insert id="saveUser" parameterType="com.tcent.pojo.User">
		insert into t_user(`last_name`,`sex`) values(#{lastName},#{sex})
	</insert>

3.2.2、更新用戶

@Override
	public int updateUser(User user) {
		SqlSession session = sqlSessionFactory.openSession();
		try {

			int result = session.update("com.tcent.pojo.User.updateUser", user);
			session.commit();
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
		return 0;
	}

<!-- 
		update標籤定義一個update語句
	 -->
	<update id="updateUser" parameterType="com.tcent.pojo.User">
		update t_user set last_name = #{lastName},sex = #{sex} where id = #{id}
	</update>

3.2.3、根據id刪除用戶

@Override
	public int deleteUserById(int id) {
		SqlSession session = sqlSessionFactory.openSession();

		try {
			int result = session.delete("com.tcent.pojo.User.deleteUserById", id);
			session.commit();
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}

		return 0;
	}

<!-- 
		delete標籤定義delete語句
		parameterType		設置參數的類型(可選)	
	 -->
	<delete id="deleteUserById" parameterType="int">
		delete from t_user where id = #{id}	
	</delete>

3.2.4、根據id搜索用戶

@Override
	public User queryUserById(int id) {
		SqlSession session = sqlSessionFactory.openSession();

		try {
			return session
					.selectOne("com.tcent.pojo.User.selectUserById", id);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}

		return null;
	}

<!-- 
		select 定義select查詢語句
			id			給你要定義的sql語句,設置一個唯一的id值。
			resultType	查詢完返回的類型
			#{id}		這是一個佔位符
	 -->
	<select id="selectUserById" resultType="com.tcent.pojo.User">
		select id,last_name lastName,sex from t_user where id = #{id}
	</select>

3.2.5、搜索全部用戶

@Override
	public List<User> queryUsers() {
		SqlSession session = sqlSessionFactory.openSession();

		try {
			return session.selectList("com.tcent.pojo.User.queryUsers");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}

		return null;
	}

	<!-- 
			id		定義一個唯一標識
			resultType	定義查詢返回的類型
	 -->
	<select id="queryUsers" resultType="com.tcent.pojo.User">
		select id,last_name lastName,sex from t_user
	</select>

3.3、實現UserDao接口

public class UserDaoImpl implements UserDao {

	private SqlSessionFactory sqlSessionFactory;

	public UserDaoImpl(SqlSessionFactory sqlSessionFactory) {
		super();
		this.sqlSessionFactory = sqlSessionFactory;
	}

	public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
		this.sqlSessionFactory = sqlSessionFactory;
	}

	@Override
	public int saveUser(User user) {
		SqlSession session = sqlSessionFactory.openSession();
		try {
			// 執行插入
			int result = session.insert("com.tcent.pojo.User.saveUser", user);
			session.commit();
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
		return 0;
	}

	@Override
	public User queryUserById(int id) {
		SqlSession session = sqlSessionFactory.openSession();

		try {
			return session
					.selectOne("com.tcent.pojo.User.selectUserById", id);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}

		return null;
	}

	@Override
	public List<User> queryUsers() {
		SqlSession session = sqlSessionFactory.openSession();

		try {
			return session.selectList("com.tcent.pojo.User.queryUsers");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}

		return null;
	}

	@Override
	public int deleteUserById(int id) {
		SqlSession session = sqlSessionFactory.openSession();

		try {
			int result = session.delete("com.tcent.pojo.User.deleteUserById", id);
			session.commit();
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}

		return 0;
	}

	@Override
	public int updateUser(User user) {
		SqlSession session = sqlSessionFactory.openSession();
		try {

			int result = session.update("com.tcent.pojo.User.updateUser", user);
			session.commit();
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
		return 0;
	}

}

3.4、編寫UserDao測試

public class UserDaoTest {

	@Test
	public void testSaveUser() throws IOException {
		// 讀取mybatis的核心配置文件
		InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
		// 通過SqlSessionFactoryBuilder創建一個SqlSessionFactory實例(只有一個實例)
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
				.build(is);
		is.close();
		
		UserDao userDao = new UserDaoImpl(sqlSessionFactory);
		userDao.saveUser(new User(0, "aaaaa", 1));
	}

	@Test
	public void testQueryUserById() throws IOException {
		// 讀取mybatis的核心配置文件
		InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
		// 通過SqlSessionFactoryBuilder創建一個SqlSessionFactory實例(只有一個實例)
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
				.build(is);
		is.close();
		
		UserDao userDao = new UserDaoImpl(sqlSessionFactory);
		User user = userDao.queryUserById(1);
		System.out.println( user );
	}

	@Test
	public void testQueryUsers() throws IOException {
		// 讀取mybatis的核心配置文件
		InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
		// 通過SqlSessionFactoryBuilder創建一個SqlSessionFactory實例(只有一個實例)
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
				.build(is);
		is.close();
		
		UserDao userDao = new UserDaoImpl(sqlSessionFactory);
		System.out.println( userDao.queryUsers() );
	}

	@Test
	public void testDeleteUserById() throws IOException {
		// 讀取mybatis的核心配置文件
		InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
		// 通過SqlSessionFactoryBuilder創建一個SqlSessionFactory實例(只有一個實例)
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
				.build(is);
		is.close();
		
		UserDao userDao = new UserDaoImpl(sqlSessionFactory);
		userDao.deleteUserById(3);
	}

	@Test
	public void testUpdateUser() throws IOException {
		// 讀取mybatis的核心配置文件
		InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
		// 通過SqlSessionFactoryBuilder創建一個SqlSessionFactory實例(只有一個實例)
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
				.build(is);
		is.close();
		
		UserDao userDao = new UserDaoImpl(sqlSessionFactory);
		userDao.updateUser(new User(3, "bbbbb", 0));
	}

}

3.5插入記錄並返回主鍵

<!-- 
		insert標籤定義insert語句
		
		useGeneratedKeys="true"	表示插入之後返回數據庫生成的主鍵id值。	
		keyProperty="id"		表示把返回的數據庫的id值,注入到 bean對象的哪個屬性中(id屬性)
	 -->
	<insert id="saveUser" useGeneratedKeys="true" keyProperty="id" parameterType="com.tcent.pojo.User">
		insert into t_user(`last_name`,`sex`) values(#{lastName},#{sex})
	</insert>

3.6<selectKey>  標籤的使用

selectKey標籤可以用來定義sql語句,在其他語句之前或之後執行。

<insert id="saveUser" parameterType="com.tcent.pojo.User">
		<!-- selectKey 標籤定義sql語句,在父標籤sql的前後或後面執行。
				order 屬性設置selectKey語句執行的順序
					BEFORE		之前
					AFTER		之後
				keyProperty="id"	屬性設置返回的主鍵值注入到bean對象的id屬性中
		 -->
		<selectKey order="AFTER" keyProperty="id" resultType="int">
			SELECT LAST_INSERT_ID()
		</selectKey>
		insert into t_user(`last_name`,`sex`) values(#{lastName},#{sex})
	</insert>

4Mapper接口方式的mybatis的增,刪,改,查實現

4.1Mapper接口編程的命名習慣

一般你的實體bean對象叫 User

你的接口叫 UserMapper

你的配置文件命名,一般也叫 UserMapper.xml

4.2Mapper接口開發有四個開發規範**必須遵守**

1mapper.xml配置文件的名稱空間,必須是接口的全類名

2mapper.xml配置文件中sql語句的id定義的值。必須跟方法名一致。

3mapper.xml配置文件,參數類型必須和方法的參數類型一致。

4mapper.xml配置文件,返回類型必須與接口方法的返回值類型一致。

4.3、編寫Mapper接口

public interface UserMapper {

	public int saveUser(User user);

	public User queryUserById(int id);

	public List<User> queryUsers();

	public int deleteUserById(int id);

	public int updateUser(User user);

}

4.5、編寫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">
<!-- 
	namespace 屬性一般情況下。
		一種定義規則:
			一種是使用對應的javaBean的全類名
			一種是使用Mapper接口的全類名
 -->
<mapper namespace="com.tcent.dao.UserMapper">

	<!-- 
		select 定義select查詢語句
			id			給你要定義的sql語句,設置一個唯一的id值。
			resultType	查詢完返回的類型
			#{id}		這是一個佔位符
	 -->
	
<!-- 	
		使用Mapper接口的方式需要遵守四個規範:
			1、mapper配置文件名稱空間值必須是mapper接口的全類名
			2、id的值必須和方法名一致。
			3、參數類型必須一致。
			4、返回值的類型也必須一致。
-->
	<select id="queryUserById" parameterType="int" resultType="com.tcent.pojo.User">
		select id,last_name,sex from t_user where id = #{id}		
	</select>
	
	<!-- 
			id		定義一個唯一標識
			resultType	定義查詢返回的類型
	 -->
	<select id="queryUsers" resultType="com.tcent.pojo.User">
		select id,last_name lastName,sex from t_user
	</select>
	
	<!-- 
		delete標籤定義delete語句
		parameterType		設置參數的類型(可選)	
	 -->
	<delete id="deleteUserById" parameterType="int">
		delete from t_user where id = #{id}	
	</delete>
	
	<!-- 
		update標籤定義一個update語句
	 -->
	<update id="updateUser" parameterType="com.tcent.pojo.User">
		update t_user set last_name = #{lastName},sex = #{sex} where id = #{id}
	</update>
	
	<!-- 
		insert標籤定義insert語句
		
		useGeneratedKeys="true"	表示插入之後返回數據庫生成的主鍵id值。	
		keyProperty="id"		表示把返回的數據庫的id值,注入到 bean對象的哪個屬性中(id屬性)
	 -->
<!-- 	<insert id="saveUser" useGeneratedKeys="true" keyProperty="id" parameterType="com.tcent.pojo.User"> -->
<!-- 		insert into t_user(`last_name`,`sex`) values(#{lastName},#{sex}) -->
<!-- 	</insert> -->
	<insert id="saveUser" parameterType="com.tcent.pojo.User">
		<!-- selectKey 標籤定義sql語句,在父標籤sql的前後或後面執行。
				order 屬性設置selectKey語句執行的順序
					BEFORE		之前
					AFTER		之後
				keyProperty="id"	屬性設置 	返回的主鍵值	注入到bean對象的id屬性中
		 -->
		<selectKey order="AFTER" keyProperty="id" resultType="int">
			SELECT LAST_INSERT_ID()
		</selectKey>
		insert into t_user(`last_name`,`sex`) values(#{lastName},#{sex})
	</insert>
	
</mapper>

4.6Mapper接口的測試:

public class UserMapperTest {

	@Test
	public void testSaveUser() throws IOException {
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
				.build(Resources.getResourceAsStream("mybatis-config.xml"));
		// 創建Session對象
		SqlSession session = sqlSessionFactory.openSession();
		try {
			// 從Session中獲取到UserMapper實例類
			UserMapper userMapper = session.getMapper(UserMapper.class);
			User user = new User(0, "bbbb32222", 0);
			userMapper.saveUser(user);
			System.out.println(user);
			session.commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
	}

	@Test
	public void testQueryUserById() throws IOException {
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
				.build(Resources.getResourceAsStream("mybatis-config.xml"));
		// 創建Session對象
		SqlSession session = sqlSessionFactory.openSession();
		try {
			// 從Session中獲取一上UserMapper實例類
			UserMapper userMapper = session.getMapper(UserMapper.class);
			User user = userMapper.queryUserById(1);
			System.out.println(user);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
	}

	@Test
	public void testQueryUsers() throws IOException {
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
				.build(Resources.getResourceAsStream("mybatis-config.xml"));
		// 創建Session對象
		SqlSession session = sqlSessionFactory.openSession();
		try {
			// 從Session中獲取一上UserMapper實例類
			UserMapper userMapper = session.getMapper(UserMapper.class);
			List<User> users = userMapper.queryUsers();
			System.out.println(users);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
	}

	@Test
	public void testDeleteUserById() throws IOException {
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
				.build(Resources.getResourceAsStream("mybatis-config.xml"));

		SqlSession session = sqlSessionFactory.openSession();
		try {
			UserMapper userMapper = session.getMapper(UserMapper.class);
			userMapper.deleteUserById(7);
			session.commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
	}

	@Test
	public void testUpdateUser() throws IOException {
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
				.build(Resources.getResourceAsStream("mybatis-config.xml"));
		// 創建Session對象
		SqlSession session = sqlSessionFactory.openSession();
		try {
			// 從Session中獲取一上UserMapper實例類
			UserMapper userMapper = session.getMapper(UserMapper.class);
			User user = new User(7, "aaaa2222", 0);
			userMapper.updateUser(user);
			session.commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
	}

}

5mybatis的核心配置之properties

mybatis-config.xml配置文件

 

需要有一個單獨的jdbc.properties屬性配置文件:

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

<!-- properties 可以配置鍵值對經常配置jdbc四個連接屬性 
	
		properties標籤主要是用來引入單獨的屬性配置文件(主要是jdbc屬性配置文件)。
		如果properties標籤中定義的鍵值對和引入的屬性配置文件的鍵名相同,引入屬性值就會覆蓋掉子標籤propery中定義的值
	-->
	<properties resource="jdbc.properties">
		<property name="username" value="root"/>
		<property name="password" value="root"/>
		<property name="url" value="jdbc:mysql://localhost:3306/mybatis1234121"/>
		<property name="driver" value="com.mysql.jdbc.Driver"/>
	</properties>

6mybatis的核心配置之settings

 

這是 MyBatis 中極爲重要的調整設置,它們會改變 MyBatis 的運行時行爲。下表描述了設置中各項的意圖、默認值等。

6.1、所有mybatissettings設置選項

 

設置參數

描述

有效值

默認值

cacheEnabled

該配置影響的所有映射器中配置的緩存的全局開關。

true | false

true

lazyLoadingEnabled

延遲加載的全局開關。當開啓時,所有關聯對象都會延遲加載。 特定關聯關係中可通過設置fetchType屬性來覆蓋該項的開關狀態。】‘。

true | false

false

aggressiveLazyLoading

當啓用時,對任意延遲屬性的調用會使帶有延遲加載屬性的對象完整加載;反之,每種屬性將會按需加載。

true | false

true

multipleResultSetsEnabled

是否允許單一語句返回多結果集(需要兼容驅動)。

true | false

true

useColumnLabel

使用列標籤代替列名。不同的驅動在這方面會有不同的表現, 具體可參考相關驅動文檔或通過測試這兩種不同的模式來觀察所用驅動的結果。

true | false

true

useGeneratedKeys

允許 JDBC 支持自動生成主鍵,需要驅動兼容。 如果設置爲 true 則這個設置強制使用自動生成主鍵,儘管一些驅動不能兼容但仍可正常工作(比如 Derby)。

true | false

False

autoMappingBehavior

指定 MyBatis 應如何自動映射列到字段或屬性。 NONE 表示取消自動映射;PARTIAL 只會自動映射沒有定義嵌套結果集映射的結果集。 FULL 會自動映射任意複雜的結果集(無論是否嵌套)。

NONE, PARTIAL, FULL

PARTIAL

autoMappingUnknownColumnBehavior

Specify the behavior when detects an unknown column (or unknown property type) of automatic mapping target.

· NONE: Do nothing

· WARNING: Output warning log (The log level of'org.apache.ibatis.session.AutoMappingUnknownColumnBehavior'must be set to WARN)

· FAILING: Fail mapping (Throw SqlSessionException)

NONE, WARNING, FAILING

NONE

defaultExecutorType

配置默認的執行器。SIMPLE 就是普通的執行器;REUSE 執行器會重用預處理語句(prepared statements); BATCH 執行器將重用語句並執行批量更新。

SIMPLE REUSE BATCH

SIMPLE

defaultStatementTimeout

設置超時時間,它決定驅動等待數據庫響應的秒數。

Any positive integer

Not Set (null)

defaultFetchSize

Sets the driver a hint as to control fetching size for return results. This parameter value can be override by a query setting.

Any positive integer

Not Set (null)

safeRowBoundsEnabled

允許在嵌套語句中使用分頁(RowBounds)。 If allow, set the false.

true | false

False

safeResultHandlerEnabled

允許在嵌套語句中使用分頁(ResultHandler)。 If allow, set the false.

true | false

True

mapUnderscoreToCamelCase

是否開啓自動駝峯命名規則(camel case)映射,即從經典數據庫列名 A_COLUMN 到經典 Java 屬性名 aColumn 的類似映射。

true | false

False

localCacheScope

MyBatis 利用本地緩存機制(Local Cache)防止循環引用(circular references)和加速重複嵌套查詢。 默認值爲 SESSION,這種情況下會緩存一個會話中執行的所有查詢。 若設置值爲 STATEMENT,本地會話僅用在語句執行上,對相同 SqlSession 的不同調用將不會共享數據。

SESSION | STATEMENT

SESSION

jdbcTypeForNull

當沒有爲參數提供特定的 JDBC 類型時,爲空值指定 JDBC 類型。 某些驅動需要指定列的 JDBC 類型,多數情況直接用一般類型即可,比如 NULL、VARCHAR 或 OTHER。

JdbcType enumeration. Most common are: NULL, VARCHAR and OTHER

OTHER

lazyLoadTriggerMethods

指定哪個對象的方法觸發一次延遲加載。

A method name list separated by commas

equals,clone,hashCode,toString

defaultScriptingLanguage

指定動態 SQL 生成的默認語言。

A type alias or fully qualified class name.

org.apache.ibatis.scripting.xmltags.XMLDynamicLanguageDriver

callSettersOnNulls

指定當結果集中值爲 null 的時候是否調用映射對象的 setter(map 對象時爲 put)方法,這對於有 Map.keySet() 依賴或 null 值初始化的時候是有用的。注意基本類型(int、boolean等)是不能設置成 null 的。

true | false

false

logPrefix

指定 MyBatis 增加到日誌名稱的前綴。

Any String

Not set

logImpl

指定 MyBatis 所用日誌的具體實現,未指定時將自動查找。

SLF4J | LOG4J | LOG4J2 | JDK_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGING

Not set

proxyFactory

指定 Mybatis 創建具有延遲加載能力的對象所用到的代理工具。

CGLIB | JAVASSIST

JAVASSIST (MyBatis 3.3 or above)

vfsImpl

Specifies VFS implementations

Fully qualified class names of custom VFS implementation separated by commas.

Not set

useActualParamName

Allow referencing statement parameters by their actual names declared in the method signature. To use this feature, your project must be compiled in Java 8 with -parameters option. (Since: 3.4.1)

true | false

true

7mybatis的核心配置之typeAliases

 

類型別名是爲 Java 類型設置一個短的名字。它只和 XML 配置有關,存在的意義僅在於用來減少類完全限定名的冗餘。

①、
<typeAliases>
<!-- typeAlias標籤一個一個別名去註冊 -->
<!-- 		<typeAlias type="com.tcent.pojo.User" alias="User"/> -->
</typeAliases>
	<!-- 定義了一個別名,以後User在配置文件就表示com.tcent.pojo.User類型
			一般別名,就使用類名。在使用的時候,首字母可以大小都可以
	 -->
②、
//當一個項目很大,指定包下由幾十個類,不可能一個個取別名,這裏就用到包別名,即直接引用該包下的類名即可
	<typeAliases>
			
		<!-- 自動搜索指定包下的所有類,註冊別名。那麼別名默認是類名。首字母小寫 -->
		<package name="com.tcent.pojo"/>
		<package name="com.tcent.pojo.a"/>
	</typeAliases>

如果別名有衝突。使用註解,如上面兩個包衝突 @Alias


7.1.系統提示的預定義別名

已經爲許多常見的 Java 類型內建了相應的類型別名。它們都是大小寫不敏感的,需要注意的是由基本類型名稱重複導致的特殊處理。

別名

映射的類型

_byte

byte

_long

long

_short

short

_int

int

_integer

int

_double

double

_float

float

_boolean

boolean

string

String

byte

Byte

long

Long

short

Short

int

Integer

integer

Integer

double

Double

float

Float

boolean

Boolean

date

Date

decimal

BigDecimal

bigdecimal

BigDecimal

object

Object

map

Map

hashmap

HashMap

list

List

arraylist

ArrayList

collection

Collection

iterator

Iterator

mybatis的核心配置之typeHandlers

 

類型處理器

Java 類型

JDBC 類型

BooleanTypeHandler

java.lang.Booleanboolean

數據庫兼容的 BOOLEAN

ByteTypeHandler

java.lang.Bytebyte

數據庫兼容的 NUMERIC 或 BYTE

ShortTypeHandler

java.lang.Shortshort

數據庫兼容的 NUMERIC 或 SHORT INTEGER

IntegerTypeHandler

java.lang.Integerint

數據庫兼容的 NUMERIC 或 INTEGER

LongTypeHandler

java.lang.Longlong

數據庫兼容的 NUMERIC 或 LONG INTEGER

FloatTypeHandler

java.lang.Floatfloat

數據庫兼容的 NUMERIC 或 FLOAT

DoubleTypeHandler

java.lang.Doubledouble

數據庫兼容的 NUMERIC 或 DOUBLE

BigDecimalTypeHandler

java.math.BigDecimal

數據庫兼容的 NUMERIC 或 DECIMAL

StringTypeHandler

java.lang.String

CHARVARCHAR

ClobReaderTypeHandler

java.io.Reader

-

ClobTypeHandler

java.lang.String

CLOBLONGVARCHAR

NStringTypeHandler

java.lang.String

NVARCHARNCHAR

NClobTypeHandler

java.lang.String

NCLOB

BlobInputStreamTypeHandler

java.io.InputStream

-

ByteArrayTypeHandler

byte[]

數據庫兼容的字節流類型

BlobTypeHandler

byte[]

BLOBLONGVARBINARY

DateTypeHandler

java.util.Date

TIMESTAMP

DateOnlyTypeHandler

java.util.Date

DATE

TimeOnlyTypeHandler

java.util.Date

TIME

SqlTimestampTypeHandler

java.sql.Timestamp

TIMESTAMP

SqlDateTypeHandler

java.sql.Date

DATE

SqlTimeTypeHandler

java.sql.Time

TIME

ObjectTypeHandler

Any

OTHER 或未指定類型

EnumTypeHandler

Enumeration Type

VARCHAR-任何兼容的字符串類型,存儲枚舉的名稱(而不是索引)

EnumOrdinalTypeHandler

Enumeration Type

任何兼容的 NUMERIC 或 DOUBLE 類型,存儲枚舉的索引(而不是名稱)。

 

8mybatis的核心配置之environments

8.1environments 標籤說明

<!-- environments可以配置多個數據庫環境
			default屬性表示默認使用哪個環境
	 -->
	<environments default="development">
		<!-- environment可以配置一個數據庫環境 
				id	定義這個數據庫環境的唯一標識
		 -->
		<environment id="development">

8.2transactionManager 標籤說明

 

MyBatis 中有兩種類型的事務管理器(也就是 type=”[JDBC|MANAGED]”):

· JDBC – 這個配置就是直接使用了 JDBC 的提交和回滾設置,它依賴於從數據源得到的連接來管理事務範圍。

· MANAGED – 這個配置幾乎沒做什麼。它從來不提交或回滾一個連接,而是讓容器來管理事務的整個生命週期(比如 JEE 應用服務器的上下文)。 默認情況下它會關閉連接,然而一些容器並不希望這樣,因此需要將 closeConnection 屬性設置爲 false 來阻止它默認的關閉行爲。例如:

<transactionManager type="MANAGED">
  <property name="closeConnection" value="false"/>
</transactionManager>

這兩種事務管理器類型都不需要任何屬性。它們不過是類型別名,換句話說,你可以使用 TransactionFactory 接口的實現類的完全限定名或類型別名代替它們。

8.3dataSource 標籤說明

type 屬性的值有三種: UNPOOLED  POOLED 。自定義(實現DataSourceFactory接口

 

有三種內建的數據源類型(也就是 type=”[UNPOOLED|POOLED|JNDI]”):

UNPOOLED– 這個數據源的實現只是每次被請求時打開和關閉連接。雖然一點慢,它對在及時可用連接方面沒有性能要求的簡單應用程序是一個很好的選擇。 不同的數據庫在這方面表現也是不一樣的,所以對某些數據庫來說使用連接池並不重要,這個配置也是理想的。UNPOOLED 類型的數據源僅僅需要配置以下

 

POOLED– 這種數據源的實現利用“池”的概念將 JDBC 連接對象組織起來,避免了創建新的連接實例時所必需的初始化和認證時間。 這是一種使得併發 Web 應用快速響應請求的流行處理方式。

 

JNDI-已歸入黃土

 

如果需要自定義數據庫連接池,需要實現通過需要實現接口 org.apache.ibatis.datasource.DataSourceFactory接口

9mybatis的核心配置之databaseIdProvider

MyBatis 可以根據不同的數據庫廠商執行不同的語句,這種多廠商的支持是基於映射語句中的 databaseId 屬性。 MyBatis 會加載不帶 databaseId 屬性和帶有匹配當前數據庫 databaseId 屬性的所有語句。

<databaseIdProvider type="DB_VENDOR">
		<property name="SQL Server" value="sqlserver" />
		<property name="MySQL" value="mysql" />
		<property name="DB2" value="db2" />
		<property name="Oracle" value="oracle" />
	</databaseIdProvider>

mybatis提供了一個類VendorDatabaseIdProvider,中的getDatabaseId() 方法用於獲取數據庫的標識。

property 標籤name屬性是獲取數據庫ID標識。

property 標籤value屬性是我們給mybatis定義的一個簡短的標識。

 

9.1databaseId測試

<select id="queryUserById" parameterType="int" resultType="user">
		select id,last_name,sex from t_user where id = #{id}		
	</select>
	
	<select id="queryUserById" parameterType="int" resultType="user" databaseId="mysql">
		select id,last_name,sex from t_user where id = #{id} and 1 = 1		
	</select>
	
	<select id="queryUserById" parameterType="int" resultType="user" databaseId="oracle">
		select id,last_name,sex from t_user where id = #{id}		
	</select>

10mybatis的核心配置之Mapper

<!-- 一個一個mapper配置文件引入 -->
<mappers>
  <mapper resource="org/mybatis/builder/AuthorMapper.xml"/>
  <mapper resource="org/mybatis/builder/BlogMapper.xml"/>
  <mapper resource="org/mybatis/builder/PostMapper.xml"/>
</mappers>

 <!-- 使用接口類名搜索配置文件 -->
<mappers>
  <mapper class="org.mybatis.builder.AuthorMapper"/>
  <mapper class="org.mybatis.builder.BlogMapper"/>
  <mapper class="org.mybatis.builder.PostMapper"/>
</mappers>

 <!-- 按照指定的包名去搜索,所有mapper配置文件

 注意:

 1、你的接口名和mapper配置文件名,必須一致

 2、你的mapper接口和mapper配置文件必須在同一個包下

  -->

 

<mappers>
  <package name="org.mybatis.builder"/>
</mappers>

其實有四種方式,只不過那種方式是絕對路徑,只能在自己服務器中使用,沒有了解的必要

兩個dtd文件和三個jar包下載


















...





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