MyBatis 1對1 1對多 關聯查詢
阿新 • • 發佈:2021-02-02
1、SQL
create table user ( id int primary key, name varchar(400) ); insert user info VALUES(1, 'ConstXiong1'); create table info ( user_id int primary key, name varchar(400) ); insert into info VALUES(1, '大熊'); create table article ( user_id int, title varchar(400) ); insert into article VALUES(1, '文章1'); insert into article VALUES(1, '文章2');
2、Maven 依賴
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>constxiong</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> </parent> <artifactId>mybatis</artifactId> <dependencies> <!-- MySQL 8.0.21 驅動 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.21</version> </dependency> <!-- MyBatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.5</version> </dependency> </dependencies> <build> </build> </project>
3、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>
<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://172.31.32.184:3306/constxiong?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value=" [email protected]"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="constxiong/mapper/UserMapper.xml"/>
</mappers>
</configuration>
4、Mapper 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="constxiong.mapper.UserMapper">
<select id="selectUserWithInfo" resultMap="UserWithInfo">
select user.id, user.name, info.user_id, info.name as info_name from user,info where user.id = info.user_id
</select>
<select id="selectUserWithArticles" resultMap="UserWithArticles">
select user.id, user.name, article.user_id, article.title from user,article where user.id = article.user_id
</select>
<resultMap id="UserWithInfo" type="constxiong.po.User">
<id property="id" column="id"/>
<result property="name" column="name"/>
<association property="info" javaType="constxiong.po.Info">
<id property="userId" column="user_id"/>
<result property="name" column="info_name"/>
</association>
</resultMap>
<resultMap id="UserWithArticles" type="constxiong.po.User">
<id property="id" column="id"/>
<result property="name" column="name"/>
<collection property="articles" ofType="constxiong.po.Article">
<id property="userId" column="user_id"/>
<result property="title" column="title"/>
</collection>
</resultMap>
</mapper>
5、Mapper 介面
package constxiong.mapper;
import constxiong.po.User;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
import java.util.Map;
/**
* UserMapper 介面,對映對資料庫的操作
*/
public interface UserMapper {
User selectUserWithInfo();
User selectUserWithArticles();
}
6、PO 類
package constxiong.po;
import java.util.List;
/**
* 使用者表模型
*/
public class User {
private Integer id;
private String name;
private String mc;
private Info info;
private List<Article> articles;
public User() {
}
public User(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMc() {
return mc;
}
public void setMc(String mc) {
this.mc = mc;
}
public Info getInfo() {
return info;
}
public void setInfo(Info info) {
this.info = info;
}
public List<Article> getArticles() {
return articles;
}
public void setArticles(List<Article> articles) {
this.articles = articles;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", mc='" + mc + '\'' +
", info=" + info +
", articles=" + articles +
'}';
}
}
package constxiong.po;
public class Info {
private int userId;
private String name;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Info{" +
"userId=" + userId +
", name=" + name +
'}';
}
}
package constxiong.po;
public class Article {
private int userId;
private String title;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Override
public String toString() {
return "Article{" +
"userId=" + userId +
", title='" + title + '\'' +
'}';
}
}
7、測試程式碼
String resource = "mybatis-config.xml";//xml配置檔案路徑
InputStream inputStream = Resources.getResourceAsStream(resource);//讀取配置
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//構建 SqlSessionFactory
SqlSession sqlSession = sqlSessionFactory.openSession(true);//通過 SqlSessionfactory 獲取 SqlSession
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);//通過 SqlSession 獲取 Mapper 介面
System.out.println("------ selectUserWithInfo ------");
User user = userMapper.selectUserWithInfo();
System.out.println(user);
System.out.println("------ selectUserWithArticles ------");
user = userMapper.selectUserWithArticles();
System.out.println(user);
//關閉 SqlSession
sqlSession.close();
列印結果:
------ selectUserWithInfo ------
User{id=1, name='ConstXiong1', mc='null', info=Info{userId=1, name=大熊}, articles=null}
------ selectUserWithArticles ------
User{id=1, name='ConstXiong1', mc='null', info=null, articles=[Article{userId=1, title='文章1'}, Article{userId=1, title='文章2'}]}
【Java學習資源】整理推薦
- Java 8 Stream API Demo
- Druid 使用
- 藉助 libreoffice,word 轉 pdf 體驗
- Java 動態代理
- openjdk jol 工具列印 Java 物件記憶體佈局
- Spring整合MyBatis
- MyBatis 自定義外掛
- MyBatis 延遲載入
- MyBatis 1對1 1對多 關聯查詢
- MyBatis insert 獲取自增主鍵
- MyBatis 批量插入
- 分頁外掛 Mybatis-PageHelper
- MyBatis 原生使用
- Sharding-JDBC 實現分庫分表
- JDK1.8 中的日期與時間 API
- Sharding-JDBC 實現讀寫分離