1. 程式人生 > >javaEE Mybatis,快速入門

javaEE Mybatis,快速入門

src/sqlMapConfig.xml(Mybatis的核心配置檔案):

<?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="jdbc.properties"/>
	<!-- 別名 包以其子包下所有類   頭字母大小都行-->
	<typeAliases>
		<!-- <typeAlias type="com.xxx.mybatis.pojo.User" alias="User"/> -->
		<package name="com.xxx.mybatis.pojo"/>
	</typeAliases>
	
	<!-- 連線資料庫的引數配置。和spring整合後 environments配置將廢除    -->
	<environments default="development">
		<environment id="development">
			<!-- 使用jdbc事務管理 -->
			<transactionManager type="JDBC" />
			<!-- 資料庫連線池 -->
			<dataSource type="POOLED">
				<property name="driver" value="${jdbc.driver}" />
				<property name="url" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8" />
				<property name="username" value="root" />
				<property name="password" value="123" />
			</dataSource>
		</environment>
	</environments>
	
	<!-- 載入外部實體類的Sql對映檔案 -->
	<mappers>
		<mapper resource="sqlmap/User.xml" />
		<!-- <mapper resource="sqlmap/User.xml" class="" url=""/> -->
		<!-- <mapper class="com.xxx.mybatis.mapper.UserMapper" /> -->
		<!-- <mapper url="" /> -->
		<!-- <package name="com.xxx.mybatis.mapper"/> -->
	</mappers>
	
</configuration>

sqlmap/User.xml(實體類的Sql對映檔案,配置原生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">

<!-- 配置原生Sql語句   -->
<mapper namespace="UserMapper">  <!-- 名稱空間namespace一般設定為Dao層介面全類名"com.xxx.mybatis.mapper.UserMapper" -->

	<!-- 通過ID查詢一個使用者。資料庫中表的欄位要和User實體類中的屬性保持對應 -->
	<select id="findUserById" parameterType="Integer" resultType="User">
		select * from user where id = #{v}
	</select>
	
	<!-- 根據使用者名稱稱模糊查詢使用者列表 -->
	<!-- 
		#{}表示佔位符             '%#{v}%' ==> '%'五'%'  (String型別會自動帶引號)
		${}表示字串拼接(不能防SQL注入)  '%${value}%' ==> '%五%'   ${value}中只能填value。   "%"#{haha}"%"可以防SQL注入
	 -->
	<select id="findUserByUsername" parameterType="String" resultType="com.xxx.mybatis.pojo.User">
		select * from user where username like "%"#{haha}"%"
	</select>
	
	<!-- 新增使用者 -->
	<insert id="insertUser" parameterType="com.xxx.mybatis.pojo.User">
		<!-- 插入成功後,將生成的主鍵id注入到user物件中。 keyProperty的"id"要和User實體類中的屬性保持一致 -->
		<selectKey keyProperty="id" resultType="Integer" order="AFTER"> <!-- MySql中的自增主鍵用AFTER(先插入,後生成主鍵)。UUID用BEFORE -->
			select LAST_INSERT_ID()
		</selectKey>
		insert into user (username,birthday,address,sex) 
		values (#{username},#{birthday},#{address},#{sex})
		<!-- #{username}中的"username"要和User實體類中的屬性名保持對應 -->
	</insert>
	
	<!-- 更新 -->
	<update id="updateUserById" parameterType="com.xxx.mybatis.pojo.User">
		update user 
		set username = #{username},sex = #{sex},birthday = #{birthday},address = #{address}
		where id = #{id}
	</update>
	
	<!-- 刪除 -->
	<delete id="deleteUserById" parameterType="Integer">
		delete from user where id = #{vvvvv}
	</delete>

</mapper>

MybatisTest.java(測試類):

package com.xxx.mybatis.junit;

import java.io.InputStream;
import java.util.Date;
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.xxx.mybatis.pojo.User;

public class MybatisTest {
	
	@Test
	public void testMybatis() throws Exception {
		//載入核心配置檔案
		String path = "sqlMapConfig.xml";
		InputStream in = Resources.getResourceAsStream(path);
		//建立SqlSessionFactory
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
		//建立SqlSession
		SqlSession sqlSession = sqlSessionFactory.openSession();
		
		//執行Sql語句   ("UserMapper"是User.xml中mapper的名稱空間名;"findUserById"是User.xml中配置的sql語句的id)
		User user = sqlSession.selectOne("UserMapper.findUserById", 10);
		
		System.out.println(user);
	}
	
	//根據使用者名稱稱模糊查詢使用者列表
	@Test
	public void testfindUserByUsername() throws Exception {
		//載入核心配置檔案
		String path = "sqlMapConfig.xml";
		InputStream in = Resources.getResourceAsStream(path);
		//建立SqlSessionFactory
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
		//建立SqlSession
		SqlSession sqlSession = sqlSessionFactory.openSession();
		
		//執行Sql語句 
		List<User> users = sqlSession.selectList("UserMapper.findUserByUsername", "五");
		for (User user2 : users) {
			System.out.println(user2);
		}
	}
	
	//新增使用者
	@Test
	public void testInsertUser() throws Exception {
		//載入核心配置檔案
		String path = "sqlMapConfig.xml";
		InputStream in = Resources.getResourceAsStream(path);
		//建立SqlSessionFactory
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
		//建立SqlSession
		SqlSession sqlSession = sqlSessionFactory.openSession();
		
		//執行Sql語句 
		User user = new User();
		user.setUsername("張三");
		user.setBirthday(new Date());
		user.setAddress("sadfsafsafs");
		user.setSex("男");
		int i = sqlSession.insert("UserMapper.insertUser", user);  //返回受影響行數
		
		sqlSession.commit();  //提交事務才會生效
		System.out.println(user.getId());  //需要在User.xml中的Mapper中配置<selectKey />標籤才能將插入後的id賦給user物件。
	}
	
	//更新使用者
	@Test
	public void testUpdateUserById() throws Exception {
		//載入核心配置檔案
		String path = "sqlMapConfig.xml";
		InputStream in = Resources.getResourceAsStream(path);
		//建立SqlSessionFactory
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
		//建立SqlSession
		SqlSession sqlSession = sqlSessionFactory.openSession();
		
		//執行Sql語句 
		User user = new User();
		user.setId(29);  //根據id修改使用者,必須設定id
		user.setUsername("張三292929");
		user.setBirthday(new Date());
		user.setAddress("222222sadfsafsafs");
		user.setSex("女");
		int i = sqlSession.update("UserMapper.updateUserById", user);
		
		sqlSession.commit();  //提交事務才會生效
	}
	
	//刪除
	@Test
	public void testDelete() throws Exception {
		//載入核心配置檔案
		String path = "sqlMapConfig.xml";
		InputStream in = Resources.getResourceAsStream(path);
		//建立SqlSessionFactory
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
		//建立SqlSession
		SqlSession sqlSession = sqlSessionFactory.openSession();
		
		sqlSession.delete("UserMapper.deleteUserById", 29);
		
		sqlSession.commit(); //提交事務才會生效
	}
	
}