MyBatis關聯查詢簡單示例

首先在數據庫bookstore中創建三張表,分別是BSuser,author,readerjava

CREATE TABLE `author` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `realName` varchar(20) COLLATE utf8_bin DEFAULT NULL,
  `userID` int(11) DEFAULT NULL,
  `IDCard` varchar(20) COLLATE utf8_bin DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

CREATE TABLE `BSuser` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `userName` varchar(20) COLLATE utf8_bin DEFAULT NULL,
  `password` varchar(20) COLLATE utf8_bin DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

CREATE TABLE `reader` (
  `visitID` int(11) NOT NULL AUTO_INCREMENT,
  `userID` int(11) DEFAULT NULL,
  `visitDate` datetime DEFAULT NULL,
  `visitIP` varchar(100) COLLATE utf8_bin DEFAULT NULL,
  PRIMARY KEY (`visitID`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

        1.聯合查詢
sql

            新建author.xml    添加數據庫

<select id="selectAuthorJoin" resultMap="AuthorMap">
	select * from author inner join BSuser 
		on BSuser.id=author.userID
</select>

   上述代碼中resultMap="AuthorMap" 因此得在上述代碼前添加對resultMap的描述session

<resultMap id="AuthorMap" type="Author">
		<id property="id" column="author.id" />
		<result property="realName" column="realName" />
		<result property="IDCard" column="IDCard" />
		<--! association 裏寫了對關聯屬性的相關描述-->
		<association property="bsuser" column="userID"  <--! bsuser是author類定義的一個屬性-->
			javaType="BSuser">
			<id property="id" column="bsuser.id" />
			<result property="userName" column="userName" />
			<result property="password" column="password" />
		</association>
		
	</resultMap>

        接着新建一個測試類
app

    

public static void main(String[] args) {
		String resource = "kobe/book/map/MyBatisConfig.xml";
		Reader reader = null;
		SqlSession session;
		try {
			reader = Resources.getResourceAsReader(resource);
		} catch (IOException e) {
			e.printStackTrace();
		}
		SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder().build(reader);
		session = sqlMapper.openSession();
		try{
			List<Author> ap=session.selectList("selectAuthorJoin");//聯合查詢與構造查詢
			for(Author temp:ap)
			{
				System.out.println("做者真實姓名="+temp.getRealName()+
				    "對應的用戶名="+temp.getbsuser().getUserName()); 
			}
			
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			session.close();
		}	
	}

    以上即是MyBatis的聯合查詢的例子框架

    接着是MyBatis的構造查詢,構造查詢的sql語句與聯合查詢相同,不一樣點在於sql語句中的            resultMap="AuthorMapByCon"  而此resultMap的association有所不一樣測試

<association property="bsuser" column="userID" javaType="BSuser">
	<constructor>
		<arg column="userName" javaType="String" />
		<arg column="password" javaType="String" />
	</constructor>
</association>

再次執行測試代碼。ui

最後子查詢,子查詢的sql語句爲code

<select id="selectAuthor" resultMap="AuthorSubMap">
		select * from author 
	</select>

    resultMap爲xml

<resultMap id="AuthorSubMap" type="Author">
		<id property="id" column="author.id" />
		<result property="realName" column="realName" />
		<result property="IDCard" column="IDCard" />
		<association property="bsuser" column="userID"
			javaType="bsuser" select="findById">
		</association>
	</resultMap>

    子查詢的測試代碼把上面測試代碼try的代碼改成

try{
		List<Author> ap=session.selectList("selectAuthor");//子查詢
		for(Author temp:ap)
		{ 
			System.out.println("做者真實姓名="+temp.getRealName());
			System.out.println("用戶名="+temp.getbsuser().getUserName());
		}
			
	}

    運行測試代碼,發如今控制檯打印了兩條sql語句,子查詢雖然進行了N+1次查詢,可是佔用資源卻可大可小,由於持久化框架MyBatis有懶加載機制,由於懶加載默認是不開啓的,因此你需在MyBatis的基本配置文件裏把lazyLoadingEnabled的value值改爲true並且把aggressiveLazyLoading的value改成false。懶加載機制能夠控制查詢次數,須要時再查詢,不須要時不查詢,運用合理的話,子查詢能比聯合查詢效率更高。

    以上即是MyBatis的關聯查詢,歡迎指出不足之處,互相交流,謝謝。

相關文章
相關標籤/搜索