MyBatis初探一

1、MyBatis介紹

mybatis(持久層框架3.2.6 or 3.2.7)簡單執行流程html

>1.SqlMapConfig.xml(全局配置文件),配置數據源,事務和運行環境等java

>2.配置映射文件(編寫SQL語句):mapper.xml...mysql

>3.SqlSessionFactory(會話工廠)--create--->SqlSession(會話)操做數據庫發送SQL語句--->Executor(執行器接口,包含基本執行器和緩存執行器)SqlSession內部經過執行器操做數據庫--->MappedStatement(底層封裝對象)對SQL語句,輸入參數,輸出結果類型sql

參考資料:數據庫

http://www.mybatis.org/mybatis-3/zh/index.html
<a href="http://www.mybatis.org/mybatis-3/zh/index.html">mybatis中文參考網站(一些屬性定義方式,類型關係,類型映射等)<a>

2、MyBatis知識點

1.mybatis->dao層緩存

2.mybatis->輸入映射,輸出映射mybatis

3.mybatis->動態輸出app

4.mybatis->關係映射(1-1,1-N,N-N)框架

5.mybatis->延遲加載dom

6.mybatis->查詢緩存(一級緩存,二級緩存)

7.mybatis->整合Spring

8.mybatis->逆向工程

3、Mybatis初探( 單表實體類增刪改查 )

  1. 加入jar:mybatis-3.2.6.jar或者mybatis-3.2.7.jar和日誌包(log4j,commons-logging)

  2. 建立數據庫表和全局配置文件SqlMapConfig.xml

USE `shop`;

/*Table structure for table `users` */

DROP TABLE IF EXISTS `users`;

CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(500) DEFAULT NULL,
  `sex` varchar(500) DEFAULT NULL,
  `birth` date DEFAULT NULL,
  `address` varchar(500) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
#db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/shop?characterEncoding=utf-8
jdbc.username=root
jdbc.password=root
<?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>
  <!-- 和Spring整合以後environments再也不須要使用 -->
  <environments default="development">
  
    <environment id="development">
      <transactionManager type="JDBC"/><!-- 使用JDBC的事務 -->
      <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>
    <mapper resource="sqlmap/Users.xml"/>
    <mapper resource="mapper/UsersMapper.xml"/>
  </mappers>
</configuration>

3.編寫實體JavaBean類和Mapper.xml對應文件

package com.ts.domain;

import java.util.Date;

public class Users {
	
	public Users() {}

	public Users(String name, String sex, Date birth, String address) {
		this.name = name;
		this.sex = sex;
		this.birth = birth;
		this.address = address;
	}

	private int id;
	
	private String name;
	
	private String sex;
	
	private Date birth;
	
	private String address;

	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 String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	public Date getBirth() {
		return birth;
	}

	public void setBirth(Date birth) {
		this.birth = birth;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	@Override
	public String toString() {
		return "Users [id=" + id + ", name=" + name + ", sex=" + sex + ", birth=" + birth + ", address=" + address
				+ "]";
	}
}
<?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:命名空間 -->
<mapper namespace="Users">
	
	<!-- MappedStatement的ID -->
	<!--#{}:佔位符 接收輸入的參數
	
		parameterType:輸入參數類型
		#{id}:參數名稱是id
		
		resultType:輸出結果類型
		返回一個JavaBean
	-->
	<select id="findUserById" parameterType="int" resultType="com.ts.domain.Users">
		select * from Users where id = #{id}
	</select>
	
	<!-- 
		${}:拼接符,拼接SQL字符串,${}中只能使用value,會有SQL注入問題,不建議使用
	 -->
	<select id="findUsersByName" parameterType="String" resultType="com.ts.domain.Users">
		select * from Users where name like '%${value}%'
	</select>
	
	<!-- 添加用戶:返回自增主鍵值 ,只適用自增主鍵
		 keyProperty="id"返回映射Java屬性
		 order="AFTER"執行順序
		 resultType="int" 返回類型
		 
		 uuid:
		 <selectKey keyProperty="id" order="BEFORE" resultType="java.lang.String">
			select uuid
		</selectKey> 
	-->
	<insert id="insertUser" parameterType="com.ts.domain.Users">
		<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
			select LAST_INSERT_ID()
		</selectKey> 
		insert into Users(name,birth,sex,address) values(#{name},#{birth},#{sex},#{address})
	</insert>
	
	<!-- 刪除用戶 -->
	<delete id="deleteUser" parameterType="int">
		delete from Users where id = #{id}
	</delete>
	
	<!-- 更新用戶 -->
	<update id="updateUser" parameterType="com.ts.domain.Users">
		update Users set name = #{name},sex = #{birth},birth = #{birth},address =#{address}  where id = #{id}
	</update>

</mapper>

4.測試增刪改查代碼

public class IMybatis {

	/**
	 * 需求:
	 * 根據ID查詢單個用戶
	 * 根據用戶名稱模糊查詢用戶
	 * 添加用戶
	 * 刪除用戶
	 * 更新用戶
	 * @throws Exception 
	 */
	private static SqlSessionFactory sqlSessionFactory;

	@Before
	public void before() throws IOException{
		//經過輸入流讀取全局配置信息建立工廠
		String resource = "SqlMapConfig.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

	}
	
	/**
	 *  根據ID查詢單個用戶
	 * @throws Exception
	 */
	@Test
	public void findUserById() throws Exception{
		//獲取SqlSession會話
		SqlSession sqlSession = sqlSessionFactory.openSession();
		//查詢一條記錄,命名空間 + id
		Users user = sqlSession.selectOne("Users.findUserById",1);
		System.out.println(user);
		//釋放資源鏈接
		sqlSession.close();
	}


	/**
	 * 根據用戶名稱模糊查詢多條用戶
	 * @throws Exception
	 */
	@Test
	public void findUsersByName() throws Exception{
		SqlSession sqlSession = sqlSessionFactory.openSession();
		//查詢多條記錄
		List<Users> users = sqlSession.selectList("Users.findUsersByName","曉明");
		System.out.println( users.size() );
		sqlSession.close();
	}
	
	/**
	 * 添加用戶
	 * @throws Exception
	 */
	@Test
	public void insertUser() throws Exception{
		SqlSession sqlSession = sqlSessionFactory.openSession();
		Users user = new Users("慧錦AAA", "女", new Date(), "北京");
		sqlSession.insert("Users.insertUser",user);
		sqlSession.commit();				
		//MySQL執行insert提交以前自動生成一個自增主鍵
		//經過MySQL函數能夠獲取剛插入記錄的自增主鍵:LAST_INSERT_ID()
		System.out.println(user.getId());	//獲取主鍵
		sqlSession.close();
	}
	
	
	/**
	 * 根據ID刪除用戶
	 * @throws Exception
	 */
	@Test
	public void deletetUser() throws Exception{
		SqlSession sqlSession = sqlSessionFactory.openSession();
		sqlSession.delete("Users.deleteUser",6);
		sqlSession.commit();			
		sqlSession.close();
	}
	
	/**
	 * 更新用戶
	 * @throws Exception
	 */
	@Test
	public void updateUser() throws Exception{
		SqlSession sqlSession = sqlSessionFactory.openSession();
		Users user = new Users();
		user.setId(5);
		user.setName("名字");
		sqlSession.update("Users.updateUser", user);
		sqlSession.commit();
		sqlSession.close();
	}
相關文章
相關標籤/搜索