Mybatis 多表間查詢之 多對一
阿新 • • 發佈:2020-08-21
0. 描述:
關於是使用MyBatis多表之間的查詢操作,案例中表t_category 是描述書的分類,表t_Book是現有書表,兩個表之間通過cid欄位建立連線,本次通過兩種方式來實現 多對一的實現,關聯和分步來實現,實際開發中是分佈來實現的。
1. 表
CREATE TABLE `t_category` ( `cid` char(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, `cname` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, `desc` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, PRIMARY KEY (`cid`) USING BTREE, UNIQUE INDEX `cname`(`cname`) USING BTREE ) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact; INSERT INTO `t_category` VALUES ('1', '程式設計', '程式設計分類'); INSERT INTO `t_category` VALUES ('3', '圖形 影象 多媒體', '圖形影象多媒體'); INSERT INTO `t_category` VALUES ('4', '作業系統/系統開發', '作業系統/系統開發'); INSERT INTO `t_category` VALUES ('458795C27E7346A8A5F1B942319297E0', '系統開發', '系統開發分類'); INSERT INTO `t_category` VALUES ('5', '資料庫', '資料庫'); INSERT INTO `t_category` VALUES ('57DE3C2DDA784B81844029A28217698C', 'Dreamweaver', 'Dreamweaver分類'); INSERT INTO `t_category` VALUES ('5F79D0D246AD4216AC04E9C5FAB3199E', 'Java Javascript', 'Java Javascript分類'); INSERT INTO `t_category` VALUES ('6', '網路與資料通訊', '網路與資料通訊!'); INSERT INTO `t_category` VALUES ('65830AB237EF428BAE9B7ADC78A8D1F6', 'Unix', 'Unix分類'); INSERT INTO `t_category` VALUES ('922E6E2DB04143D39C9DDB26365B3EE8', 'C C++ VC VC++', 'C C++ VC VC++分類'); CREATE TABLE `t_book` ( `bid` char(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, `bname` varchar(200) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, `author` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, `price` decimal(8, 2) DEFAULT NULL, `press` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, `cid` char(32) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, PRIMARY KEY (`bid`) USING BTREE, INDEX `FK_t_book_t_category`(`cid`) USING BTREE, CONSTRAINT `FK_t_book_t_category` FOREIGN KEY (`cid`) REFERENCES `t_category` (`cid`) ON DELETE RESTRICT ON UPDATE RESTRICT ) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact; INSERT INTO `t_book` VALUES ('52B0EDFF966E4A058BDA5B18EEC698C4', '亮劍Java Web專案開發案例導航(含DVD光碟1張)', '朱雪琴', 69.00, '電子工業出版社', '5F79D0D246AD4216AC04E9C5FAB3199E'); INSERT INTO `t_book` VALUES ('5315DA60D24042889400AD4C93A37501', 'Spring 3.x企業應用開發實戰(含CD光碟1張)', '陳雄華', 90.00, '電子工業出版社', '1'); INSERT INTO `t_book` VALUES ('56B1B7D8CD8740B098677C7216A673C4', '瘋狂 Java 程式設計師的基本修養(《瘋狂Java講義》最佳拍檔,掃清知識死角,夯實基本功)', '李剛', 59.00, '電子工業出版社', '5F79D0D246AD4216AC04E9C5FAB3199E'); INSERT INTO `t_book` VALUES ('57B6FF1B89C843C38BA39C717FA557D6', '了不起的Node.js: 將JavaScript進行到底(Web開發首選實時 跨多伺服器 高併發)', 'Guillermo Rauch', 79.00, '電子工業出版社', '5F79D0D246AD4216AC04E9C5FAB3199E'); INSERT INTO `t_book` VALUES ('5C68141786B84A4CB8929A2415040739', 'JavaScript高階程式設計(第3版)(JavaScript技術名著,國內JavasScript第一書,銷量超過8萬冊)', 'Nicholas C. Zakas', 99.00, '人民郵電出版社', '5F79D0D246AD4216AC04E9C5FAB3199E'); INSERT INTO `t_book` VALUES ('5EDB981339C342ED8DB17D5A198D50DC', 'Java程式效能優化', '葛一鳴', 59.00, '清華大學出版社', '5F79D0D246AD4216AC04E9C5FAB3199E'); INSERT INTO `t_book` VALUES ('A3D464D1D1344ED5983920B472826730', 'Java Web開發詳解:XML+DTD+XML Schema+XSLT+Servlet 3 0+JSP 2 2深入剖析與例項應用(含CD光碟1張)', '孫鑫', 119.00, '電子工業出版社', '5F79D0D246AD4216AC04E9C5FAB3199E'); INSERT INTO `t_book` VALUES ('A46A0F48A4F649AE9008B38EA48FAEBA', 'Java程式設計全能詞典(含DVD光碟2張)', '明日科技', 98.00, '電子工業出版社', '5F79D0D246AD4216AC04E9C5FAB3199E'); INSERT INTO `t_book` VALUES ('D0E69F85ACAB4C15BB40966E5AA545F1', 'Java併發程式設計實戰(第16屆Jolt大獎提名圖書,Java併發程式設計必讀佳作', 'Brian Goetz', 69.00, '機械工業出版社', '5F79D0D246AD4216AC04E9C5FAB3199E'); INSERT INTO `t_book` VALUES ('D2ABA8B06C524632846F27C34568F3CE', 'Java 經典例項', '達爾文', 98.00, '中國電力出版社', '5F79D0D246AD4216AC04E9C5FAB3199E'); INSERT INTO `t_book` VALUES ('D8723405BA054C13B52357B8F6AEEC24', '深入理解Java虛擬機器:JVM高階特性與最佳實踐(第2版)', '周志明', 79.00, '機械工業出版社', '5F79D0D246AD4216AC04E9C5FAB3199E'); INSERT INTO `t_book` VALUES ('DC36FD53A1514312A0A9ADD53A583886', 'JavaScript非同步程式設計:設計快速響應的網路應用【掌握JavaScript非同步程式設計必殺技,讓程式碼更具響應度! 】', 'Trevor Burnham ', 32.00, '人民郵電出版社', '5F79D0D246AD4216AC04E9C5FAB3199E'); INSERT INTO `t_book` VALUES ('DCB64DF0084E486EBF173F729A3A630A', 'Java設計模式(第2版)', 'Steven John Metsker', 75.00, '電子工業出版社', '5F79D0D246AD4216AC04E9C5FAB3199E'); INSERT INTO `t_book` VALUES ('DCB64DF0084E486EBF173F798A3A630A', 'C++ Primer中文版(第5版)', '(美)李普曼 等', 128.00, '電子工業出版社', '922E6E2DB04143D39C9DDB26365B3EE8'); INSERT INTO `t_book` VALUES ('DEE7BDC7E0E343149E3C3601D2658171', '瘋狂HTML 5/CSS 3/JavaScript講義(含CD光碟1張)', '李剛', 69.00, '電子工業出版社', '1'); INSERT INTO `t_book` VALUES ('DF4E74EEE89B43229BB8212F0B858C38', '精通Hibernate:Java物件持久化技術詳解(第2版)(含光碟1張)', '孫衛琴', 75.00, '電子工業出版社', '5F79D0D246AD4216AC04E9C5FAB3199E'); INSERT INTO `t_book` VALUES ('EA695342393C4BE48B831FA5E6B0E5C4', '編寫可維護的JavaScript《JavaScript高階程式設計》作者Nicholas Zakas最新力作,構建編碼風格手冊,幫助開發團隊從“游擊隊”走向“正規軍”)', 'Nicholas C. Zakas', 55.00, '人民郵電出版社', '5F79D0D246AD4216AC04E9C5FAB3199E'); INSERT INTO `t_book` VALUES ('F0E34313BF304CCEBF198BD4E05307B8', 'jQuery Cookbook中文版(jQuery之父鼎力推薦,社群數十位專家傾情力作', 'jQuery社群專家組', 69.00, '人民郵電出版社', '5F79D0D246AD4216AC04E9C5FAB3199E'); INSERT INTO `t_book` VALUES ('F6162799E913423EA5CB57BEC65AB1E9', 'JUnit實戰(第2版)', '塔凱文', 79.00, '人民郵電出版社', '5F79D0D246AD4216AC04E9C5FAB3199E'); INSERT INTO `t_book` VALUES ('F693239BC3B3444C8538ABE7411BB38E', 'Java Web典型模組與專案實戰大全(配光碟)', '常建功', 99.50, '清華大學出版社', '5F79D0D246AD4216AC04E9C5FAB3199E'); INSERT INTO `t_book` VALUES ('F78C94641DB4475BBA1E72A07DF9B3AE', 'JAVA面向物件程式設計', '孫衛琴 ', 65.80, '電子工業出版社', '5F79D0D246AD4216AC04E9C5FAB3199E'); INSERT INTO `t_book` VALUES ('FC232CD9B6E6411BBBB1A5B781D2C3C9', 'Java與模式(含盤)(超多例項和習題,詳解設計原則與設計模式)', '閻巨集', 88.00, '電子工業出版社', '5F79D0D246AD4216AC04E9C5FAB3199E'); INSERT INTO `t_book` VALUES ('FEC3740CF30E442A94021911A25EF0D7', 'Spring攻略(第2版)(Spring攻略(第2版))', 'Gary Mak Josh Long Daniel Rubio', 128.00, '人民郵電出版社', '5F79D0D246AD4216AC04E9C5FAB3199E'); INSERT INTO `t_book` VALUES ('FFABBED1E5254BC0B2726EC4ED8ACCDA', '深入理解OSGi:Equinox原理、應用與最佳實踐(《深入理解Java虛擬機器》作者新作!全面解讀最新OSGi R5.0規範,深入講解OSGi原理和服務,以及Equinox框架的用法和原理)', '周志明', 79.00, '機械工業出版社', '5F79D0D246AD4216AC04E9C5FAB3199E');
2. 專案搭建
1. 匯入pom.xml
依賴的jar 表的外掛 <dependencies> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.4</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> </dependencies> <build> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> <configuration> <source>11</source> <target>11</target> <encoding>UTF-8</encoding> </configuration> </plugin> </plugins> </build> </project>
2.Mybatis-config.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> <settings> <!--SQL日誌--> <setting name="logImpl" value="STDOUT_LOGGING"/> </settings> <environments default="development"> <environment id="development"> <!--事務管理器--> <transactionManager type="JDBC"/> <!--資料來源--> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://127.0.0.1:3306/kdb2"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <!-- 對映程式碼存放區 --> </configuration>
3. Mybatis 連線工具類
public class MyBatisUtil {
private static final String resource = "mybatis-config.xml";
private static SqlSessionFactory sqlSessionFactory;
static {
try {
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
// ThreadLocal是一個和執行緒相關的容器,只要是在同一個執行緒中,獲取到的必定是同一個物件
private static ThreadLocal<SqlSession> TL = new ThreadLocal<>();
public static SqlSession openSession() {
SqlSession sqlSession = TL.get();
// 當前執行緒第一次呼叫該方法
if (sqlSession == null) {
sqlSession = sqlSessionFactory.openSession();
TL.set(sqlSession);
}
return sqlSession;
}
public static void release(SqlSession sqlSession) {
if (sqlSession != null) {
sqlSession.close();
}
}
}
4. log4j 配置檔案
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<param name="Encoding" value="UTF-8" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) \n" />
</layout>
</appender>
<logger name="java.sql">
<level value="debug" />
</logger>
<logger name="org.apache.ibatis">
<level value="info" />
</logger>
<root>
<level value="debug" />
<appender-ref ref="STDOUT" />
</root>
</log4j:configuration>
5.domain
public class Book {
private String bid;
private String bname;
private String author;
private Double price;
private String press;
private String cid;
// get/set method and toString
}
public class Category {
private String cid;
private String cname;
private String desc;
// get/set method and toString
}
1.關聯查詢的方式實現
1. 實體類 Book.java
2. 主配置檔案 Mybatis-config.xml
</environments>
<mappers>
<mapper resource="cn/ccut/mapper/BookDao.xml" ></mapper>
</mappers>
3. 介面 IBookDao.java
4. BookDao.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">
<mapper namespace="cn.ccut.dao.IBookDao">
<resultMap id="books" type="cn.ccut.domain.Book">
<id property="bid" column="bid"/>
<result property="bname" column="bname"/>
<result property="author" column="author"/>
<result property="price" column="price"/>
<result property="press" column="press"/>
<result property="cid" column="cid"/>
<association property="category" column="cid" javaType="cn.ccut.domain.Category">
<id property="cid" column="tcid"/>
<result property="cname" column="tcname"></result>
<result column="desc" property="desc"></result>
</association>
</resultMap>
<select id="selectQuery" resultMap="books">
select t1.cid tcid,t1.cname tcname,t1.desc,t.* from t_book t join t_category t1 on t.cid=t1.cid and t.cid="5F79D0D246AD4216AC04E9C5FAB3199E"
</select>
</mapper>
5. 測試
public class testS {
@Test
public void fun(){
IBookDao mapper = MyBatisUtil.openSession().getMapper(IBookDao.class);
System.out.println( mapper.selectQuery("1111"));
}
}