1. 程式人生 > >mybatis進階

mybatis進階

1.輸入對映和輸出對映

Mapper.xml對映檔案中定義了操作資料庫的sql,每個sql是一個statement,對映檔案是mybatis的核心

UserMapper.xml檔案中的配置:select標籤(parameterType,resultType,resultMap),if、sql、where、foreach標籤

 

1>parameterType:傳入引數型別

簡單型別:Integer,String....使用#{}佔位符,或者${}進行sql拼接。

pojo物件:User物件,Orders物件.....使用ognl表示式解析物件欄位的值,#{}或者${}括號中的值為pojo屬性名稱

QueryVo包裝物件(User為QueryVo的屬性):

	<!-- 根據vo查
		public List<User> findByVo(QueryVo vo); -->
	<select id="findByVo" parameterType="QueryVo" resultType="User">
		select * from user where username = #{user.username}
	</select>

 

2>resultType:輸出引數型別

簡單型別:Integer,String...

pojo物件:User物件,Orders物件.....

 

3>resultMap:自動封裝輸出引數

	<!--當pojo中的屬性名與資料庫列名不對應時,我們使用resultMap手動對映,只封裝我們想要(name不同)的屬性即可 -->
	<!-- id:設定主鍵
		property:主鍵在pojo中的屬性名
		column:主鍵在資料庫中的列名 -->
	<resultMap type="Orders" id="texOrders">
		<result column="user_id" property="userId"/>
	</resultMap>
	
	<!-- 查詢訂單表order的所有資料
		public List<Orders> findAll() -->
	<select id="findAll" resultMap="texOrders" >
		select * from orders
	</select>

 

2.動態SQL

if、sql、where、foreach標籤

 

1>sql:相同sql的抽取(如:select * from user)

	<!-- sql片段抽取 -->
	<sql id="texSql">
		select * from user
	</sql>
	<select id="findByIds" resultType="User">
		<include refid="texSql"/>
        </select>

 

2>if:查詢前先進行判斷

	<!-- 根據性別和名字查詢使用者
	public List<User> findByUsernameANDSex(User user); -->
	<select id="findByUsernameANDSex" parameterType="User" resultType="user">
		<if test="username != null and username != ''">
			AND username = #{username} 
		</if>
		<if test="sex != null and sex != ''">
			AND sex = #{sex} 
		</if>
	</select>

 

3>where:去掉前and(不能去掉後and)

	<!-- 根據性別和名字查詢使用者
	public List<User> findByUsernameANDSex(User user); -->
	<select id="findByUsernameANDSex" parameterType="User" resultType="user">
		<include refid="texSql"/>
		<where>
			<if test="username != null and username != ''">
				AND username = #{username} 
			</if>
			<if test="sex != null and sex != ''">
				AND sex = #{sex} 
			</if>
		</where>
	</select>

 

4>foreach:迴圈遍歷(

當傳入的是QueryVo時,foreach中的collection值直接寫QueryVo中的屬性名即可,

當傳入的是Integer[]型別時,mybatis會將傳入名改變為array,所以collection值填寫array

當傳入的是List<Integer>型別時,mybatis會將傳入名改變為list,所以collection值填寫list

	<!-- //根據ids查詢使用者
	List<User> findByIds(QueryVo ids);
	List<User> findByIds2(Integer[] ids);//array
	List<User> findByIds3(List<Integer> ids);//list -->
	<select id="findByIds" parameterType="QueryVo" resultType="User">
		<include refid="texSql"/>
		<where>
			id in
			<foreach collection="idsList" item="ids" open="(" close=")" separator=",">
				#{ids}
			</foreach>
		</where>
	</select>
	<select id="findByIds2" parameterType="Integer" resultType="User">
		<include refid="texSql"/>
		<where>
			id in 
			<foreach collection="array" item="ids" open="(" close=")" separator=",">
				#{ids}
			</foreach>
		</where>
	</select>
	<select id="findByIds3" parameterType="Integer" resultType="User">
		<include refid="texSql"/>
		<where>
			id in
			<foreach collection="list" item="ids" open="(" close=")" separator=",">
				#{ids}
			</foreach>
		</where>
	</select>

 

3.關聯查詢(劃重點)

一對一:一個訂單隻能由一個使用者建立,一對多:一個使用者可以建立多個訂單

 

一對一查詢:使用resultMap中的association

1>在orders表中宣告user

    //表達一對一
    private User user;get/set

2>OrdersMapper.xml對映檔案中表達

	<!-- //表達一對一關係
		public List<Orders> findByOneToOne(); -->
	<resultMap type="Orders" id="resOrder">
		<id column="id" property="id"/>
		<result column="number" property="number"/>
		<!-- 一對一關係內部表達 -->
		<association property="user" javaType="User">
			<id column="user_id" property="id"/>
			<result column="username" property="username"/>
		</association>
	</resultMap>
	
	<select id="findByOneToOne" resultMap="resOrder">
		SELECT 
		o.id,
		o.number,
		o.user_id,
		u.username 
		FROM 
		orders o LEFT JOIN USER u  
		ON o.user_id = u.id
	</select>

 

一對多查詢:使用resultMap中的association

1>在User中宣告List<Orders>

	//表達一對多關係
	private List<Orders> ordList;get/set

2>UserMapper.xml對映檔案中表達

	<!--	//表達多對多關係
			public User findByMoreToMore();  -->
	<resultMap type="User" id="resUser">
		<id column="user_id" property="id"/>
		<result column="username" property="username"/>
		<!-- 表達多對多關係 -->
		<collection property="ordList" ofType="Orders">
			<id column="id" property="id"/>
			<result column="number" property="number"/>
		</collection>
	</resultMap>
	
	<select id="findByMoreToMore" resultMap="resUser">
		SELECT 
		o.id,
		o.number,
		o.user_id,
		u.username 
		FROM USER u LEFT JOIN orders o  
		ON o.user_id = u.id
	</select>

 

4.mybatis與spring的整合(劃重點)

1>整合思路

SqlSessionFactory物件應該放到spring容器中作為單例存在。

Mapper代理形式中,應該從spring容器中直接獲得mapper的代理物件。

資料庫的連線以及資料庫連線池事務管理都交給spring容器來完成

 

2>所需jar包

spring的jar包、Mybatis的jar包、Spring+mybatis的整合包、mysql資料庫驅動包、連線池包

 

3>applciationContext.xml配置檔案

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
	http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
	http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">

	<!-- 載入配置檔案 -->
   <context:property-placeholder location="classpath:db.properties" />

	<!-- 資料庫連線池 -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<property name="driverClassName" value="${jdbc.driver}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
		<property name="maxActive" value="10" />
		<property name="maxIdle" value="5" />
	</bean>

	<!-- 配置SqlSessionFactory -->
	<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
		<!-- 配置mybatis核心配置檔案 -->
		<property name="configLocation" value="sqlMapConfig.xml" />
		<!-- 配置資料來源 -->
		<property name="dataSource" ref="dataSource" />
	</bean>
	
	<!--  Mapper動態代理開發
	<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
		<property name="sqlSessionFactory" ref="sqlSessionFactoryBean"/>
		<property name="mapperInterface" value="com.imwj.mapper.UserMapper"/>
	</bean> -->
	
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<!-- 路徑基本包 -->
		<property name="basePackage" value="com.imwj.mapper"/>
	</bean>
</beans>


db.properties:
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8
jdbc.username=root
jdbc.password=123456

4>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>

	<typeAliases>
	<!-- 2. 指定掃描包,會把包內所有的類都設定別名,別名的名稱就是類名,大小寫不敏感 -->
		<package name="com.imwj.pojo" />
	</typeAliases>
	
	<mappers>
		<!-- 掃描整個包路徑 -->
		<package name="com.imwj.mapper"/>
	</mappers>
	
</configuration>

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:名稱空間,用於隔離sql,還有一個很重要的作用,後面會講 -->
<mapper namespace="com.imwj.mapper.UserMapper">

	<!-- 根據id查詢 -->
	<select id="findById" parameterType="Integer" resultType="User">
		select * from user where id = #{id}
	</select>
</mapper>

6>UserMapper.java

public interface UserMapper {
    //根據id查詢
    public User findById(Integer id);

7>測試

	@Test
	public void fun2(){
		ClassPathXmlApplicationContext apx = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
		UserMapper mapper = (UserMapper) apx.getBean("userMapper");
		User user = mapper.findById(1);
		System.out.println(user);
	}

 

6.逆向工程

簡單點說,就是通過資料庫中的單表,自動生成java程式碼。

Mybatis官方提供了逆向工程,可以針對單表自動生成mybatis程式碼(mapper.java\mapper.xml\po類)

 

2>生成檔案

3>使用

	@Test
	public void fun1(){
		ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
		UserMapper userMapper = ac.getBean(UserMapper.class);
		
		UserExample userExample = new UserExample();
		userExample.createCriteria().andUsernameLike("%張%");
		
		List<User> users = userMapper.selectByExample(userExample);
		for (User user : users) {
			System.out.println(user);
		}
	}