mybatis入門

    

mybatis介紹

    

                    MyBatis 本是apache的一個開源項目iBatis, 2010年這個項目由apache software foundation 遷移到了google code,並且改名爲MyBatis 。2013年11月遷移到Github。  

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

                   

   入門程序

                   一:創建一個java工程;

                    二:加入jar包

                        2.1:mybatis-3.2.7.jar----mybatis的核心包

                        2.2:mysql-connector-java-517-bin.jar ----數據驅動包

                        2.3:其它爲依賴包

            

                三:classpath下(src)創建log4j.properties如下:      

        mybatis默認使用log4j作爲輸出日誌信息。

# 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

    四:在classpath下(src)創建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>
    <!-- 和spring整合後 environments配置將廢除 -->
    <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/ssm?characterEncoding=utf-8" />
                <property name="username" value="root" />
                <property name="password" value="root" />
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="sqlmap/Usermapper.xml"/>
    </mappers>
</configuration>

SqlMapConfig.xmlmybatis核心配置文件,上邊文件的配置內容爲數據源、事務管理。

                五: 創建pojo類,與數據庫表對應如下:

  數據庫:

         

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(32) NOT NULL COMMENT '用戶名稱',
  `birthday` date DEFAULT NULL COMMENT '生日',
  `sex` char(1) DEFAULT NULL COMMENT '性別',
  `address` varchar(256) DEFAULT NULL COMMENT '地址',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=31 DEFAULT CHARSET=utf8;

pojo類:

public class User {
    private Integer id;
    private String username;// 用戶姓名
    private String sex;// 性別
    private Date birthday;// 生日
    private String address;// 地址

get/set……
                六: sql映射文件

        

classpath下的sqlmap目錄下創建sql映射文件User.xml

        

namespace:命名空間,用於隔離sql,還有一個很重要的作用,下一章會講   
<?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="test">

</mapper>
    

準備工作完畢,下面開始增刪改查


添加:

        在User.xml中添加

<insert id="insertUser" parameterType="domain.User">
		<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
			SELECT LAST_INSERT_ID()
		</selectKey>
		INSERT INTO USER(username,birthday,sex,address) 
			VALUES(#{username},#{birthday},#{sex},#{address})
	</insert>

添加selectKey實現將主鍵返回

keyProperty:返回的主鍵存儲在pojo中的哪個屬性

orderselectKey的執行順序,是相對與insert語句來說,由於mysql的自增原理執行完insert語句之後纔將主鍵生成,所以這裏selectKey的執行順序爲after

resultType:返回的主鍵是什麼類型

LAST_INSERT_ID():mysql的函數,返回auto_increment自增列新記錄id


  

創建測試類:    

    

	@Test
	public void testInsert() {
		// 數據庫會話實例
		SqlSession sqlSession = null;
		try {
			// 創建數據庫會話實例sqlSession
			sqlSession = sqlSessionFactory.openSession();
			// 添加用戶信息
			User user = new User();
			user.setUsername("小明");
			user.setAddress("河南");
			user.setSex("1");
			user.setPrice(1999.9f);
			sqlSession.insert("test.insertUser", user);
			//提交事務
			sqlSession.commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (sqlSession != null) {
				sqlSession.close();
			}
		}
	}
    

 Mysql使用 uuid實現主鍵

 

需要增加通過select uuid()得到uuid

<insert id="insertUser" parameterType="mybatis.po.User">

<selectKey resultType="java.lang.String" order="BEFORE"keyProperty="id">

    select uuid()

</selectKey>

insert into user(id,username,birthday,sex,address)

 values(#{id},#{username},#{birthday},#{sex},#{address})

</insert>

注意這裏使用的order是“BEFORE


刪除:

        在User.xml中添加

<!-- 刪除用戶 -->
	<delete id="deleteUserById" parameterType="int">
		delete from user where id=#{id}
	</delete>

    創建測試方法:    

    

	//會話工廠
	private SqlSessionFactory sqlSessionFactory;

	@Before
	publicvoid createSqlSessionFactory() throws IOException {
		// 配置文件
		String resource = "SqlMapConfig.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);

		// 使用SqlSessionFactoryBuilder從xml配置文件中創建SqlSessionFactory
		sqlSessionFactory = new SqlSessionFactoryBuilder()
				.build(inputStream);

	}


// 根據id刪除用戶
	@Test
	public void testDelete() {
		// 數據庫會話實例
		SqlSession sqlSession = null;
		try {
			// 創建數據庫會話實例sqlSession
			sqlSession = sqlSessionFactory.openSession();
			// 刪除用戶
			sqlSession.delete("test.deleteUserById",18);
			// 提交事務
			sqlSession.commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (sqlSession != null) {
				sqlSession.close();
			}
		}
	}

修改:

        在User.xml中添加

<!-- 更新用戶 -->
	<update id="updateUser" parameterType="mybatis.po.User">
		update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address}
		where id=#{id}
	</update>


    創建測試方法:    

    

	//會話工廠
	private SqlSessionFactory sqlSessionFactory;

	@Before
	publicvoid createSqlSessionFactory() throws IOException {
		// 配置文件
		String resource = "SqlMapConfig.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);

		// 使用SqlSessionFactoryBuilder從xml配置文件中創建SqlSessionFactory
		sqlSessionFactory = new SqlSessionFactoryBuilder()
				.build(inputStream);

	}


// 更新用戶信息
	@Test
	public void testUpdate() {
		// 數據庫會話實例
		SqlSession sqlSession = null;
		try {
			// 創建數據庫會話實例sqlSession
			sqlSession = sqlSessionFactory.openSession();
			// 添加用戶信息
			User user = new User();
			user.setId(16);
			user.setUsername("小明");
			user.setAddress("河南鄭州");
			user.setSex("1");
			user.setPrice(1999.9f);
			sqlSession.update("test.updateUser", user);
			// 提交事務
			sqlSession.commit();

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (sqlSession != null) {
				sqlSession.close();
			}
		}
	}

  

查詢(根據id查詢:):

        在User.xml中添加

<!-- 根據id獲取用戶信息 -->
	<select id="findUserById" parameterType="int"resultType="mybatis.po.User">
		select * from user where id = #{id}
	</select>

parameterType:定義輸入到sql中的映射類型,#{id}表示使用preparedstatement設置佔位符號並將輸入變量id傳到sql

resultType定義結果映射類型。

    創建測試方法:    

  

	// 根據 id查詢用戶信息
	@Test
	public void testFindUserById() {
		// 數據庫會話實例
		SqlSession sqlSession = null;
		try {
			// 創建數據庫會話實例sqlSession
			sqlSession = sqlSessionFactory.openSession();
			// 查詢單個記錄,根據用戶id查詢用戶信息
			User user = sqlSession.selectOne("test.findUserById", 10);
			// 輸出用戶信息
			System.out.println(user);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (sqlSession != null) {
				sqlSession.close();
			}
		}

	}
}

   查詢(根據用戶名查詢:):

        在User.xml中添加

<!-- 自定義條件查詢用戶列表 -->
	<select id="findUserByUsername" parameterType="java.lang.String"
			resultType="mybatis.po.User">
	   select * from user where username like '%${value}%' 
	</select>

parameterType:定義輸入到sql中的映射類型,${value}表示使用參數將${value}替換,做字符串的拼接。

注意:如果是取簡單數量類型的參數,括號中的值必須爲value

resultType定義結果映射類型。


    創建測試方法:   

// 根據用戶名稱模糊查詢用戶信息
	@Test
	publicvoid testFindUserByUsername() {
		// 數據庫會話實例
		SqlSession sqlSession = null;
		try {
			// 創建數據庫會話實例sqlSession
			sqlSession = sqlSessionFactory.openSession();
			// 查詢單個記錄,根據用戶id查詢用戶信息
			List<User> list = sqlSession.selectList("test.findUserByUsername", "張");
			System.out.println(list.size());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (sqlSession != null) {
				sqlSession.close();
			}
		}

	}





        





發佈了24 篇原創文章 · 獲贊 3 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章