准备工作:
1.创建Maven工程,还没有配置Maven的和还不会的去看这里啦:maven的下载安装与配置环境变量!!!(全网最详细)-CSDN博客
Account.java : (pojo类) (这里我们说明一下,根据我们下边的需求,我们需要将两张表查询出来的数据存到Account中,所以我们在Account这个实体类中添加了一个User的属性)
package com.by.pojo;import java.io.Serializable;public class Account implements Serializable {private Integer id;private Integer uid;private Double money;private User user;@Overridepublic String toString() {return "Account{" +"id=" + id +", uid=" + uid +", money=" + money +", user=" + user +'}';}public User getUser() {return user;}public void setUser(User user) {this.user = user;}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public Integer getUid() {return uid;}public void setUid(Integer uid) {this.uid = uid;}public Double getMoney() {return money;}public void setMoney(Double money) {this.money = money;}
}
User.java:
/** Copyright (c) 2020, 2023, All rights reserved.**/
package com.by.pojo;import java.io.Serializable;
import java.util.Date;/*** <p>Project: mybatis - User</p>* <p>Powered by scl On 2023-12-18 11:38:09</p>* <p>描述:<p>** @author 孙臣龙 [1846080280@qq.com]* @version 1.0* @since 17*/
public class User implements Serializable {private Integer id;private String username;private Date birthday;private String sex;private String address;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public Date getBirthday() {return birthday;}public void setBirthday(Date birthday) {this.birthday = birthday;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}public String getAddress() {return address;}public void setAddress(String address) {this.address = address;}@Overridepublic String toString() {return "User{" +"id=" + id +", username='" + username + '\'' +", birthday=" + birthday +", sex='" + sex + '\'' +", address='" + address + '\'' +'}';}
}
2.导入依赖到pom.xml文件中
<dependencies><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.4.5</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.12</version></dependency></dependencies><build><!-- 如果不添加此节点src/main/java目录下的所有配置文件都会被漏掉。 --><resources><resource><directory>src/main/java</directory><includes><include>**/*.xml</include></includes></resource><resource><directory>src/main/resources</directory></resource></resources></build>
3.在resources中创建log4j.properites和mybatis-config.xml
log4j.properites:
log4j.properites:# Global logging configurationlog4j.rootLogger=DEBUG, stdout# Console output...log4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
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><!--使用dev环境--><environments default="dev"><!--dev环境--><environment id="dev"><transactionManager type="JDBC"></transactionManager><!--使用连接池中的数据源--><dataSource type="POOLED"><property name="driver" value="com.mysql.jdbc.Driver"/><property name="url" value="jdbc:mysql://127.0.0.1:3305/mybatis?characterEncoding=UTF-8"/><property name="username" value="root"/><property name="password" value=""/></dataSource></environment></environments><!-- 扫描映射文件 --><mappers><mapper resource="com/by/mapper/UserMapper.xml"/></mappers></configuration>
4.创建RolerMapper接口和RoleMapper.xml文件
AccountMapper.java:
package com.by.mapper;import com.by.pojo.Account;import java.util.List;public interface AccountMapper {}
AccountMapper.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.by.mapper.AccountMapper"></mapper>
5.创建测试类MyBatisTest
/** Copyright (c) 2020, 2023, All rights reserved.**/package com.by;import com.by.mapper.RoleMapper;import com.by.pojo.Role;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.After;import org.junit.Before;import org.junit.Test;import java.io.IOException;import java.io.InputStream;import java.util.List;public class MyBatisTestRole {private InputStream inputStream;private SqlSession sqlSession;@Beforepublic void init() throws IOException {// 加载配置文件String resource = "mybatis-config.xml";inputStream = Resources.getResourceAsStream(resource);// 创建sqlSessionFActorySqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);// 获得数据的绘画实例sqlSession = sessionFactory.openSession();}@Afterpublic void close() throws IOException {inputStream.close();sqlSession.close();}}
6.数据库文件
/*
Navicat MySQL Data TransferSource Server : localhost_3306
Source Server Version : 50732
Source Host : localhost:3306
Source Database : mybatisTarget Server Type : MYSQL
Target Server Version : 50732
File Encoding : 65001Date: 2021-12-24 11:51:18
*/SET FOREIGN_KEY_CHECKS=0;-- ----------------------------
-- Table structure for account
-- ----------------------------
DROP TABLE IF EXISTS `account`;
CREATE TABLE `account` (`id` int(11) NOT NULL COMMENT '编号',`uid` int(11) DEFAULT NULL COMMENT '用户编号',`money` double DEFAULT NULL COMMENT '金额',PRIMARY KEY (`id`),KEY `FK_Reference_8` (`uid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;-- ----------------------------
-- Records of account
-- ----------------------------
INSERT INTO `account` VALUES ('1', '41', '1000');
INSERT INTO `account` VALUES ('2', '45', '1000');
INSERT INTO `account` VALUES ('3', '41', '2000');-- ----------------------------
-- Table structure for role
-- ----------------------------
DROP TABLE IF EXISTS `role`;
CREATE TABLE `role` (`ID` int(11) NOT NULL COMMENT '编号',`ROLE_NAME` varchar(30) DEFAULT NULL COMMENT '角色名称',`ROLE_DESC` varchar(60) DEFAULT NULL COMMENT '角色描述',PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;-- ----------------------------
-- Records of role
-- ----------------------------
INSERT INTO `role` VALUES ('1', '院长', '管理整个学院');
INSERT INTO `role` VALUES ('2', '总裁', '管理整个公司');
INSERT INTO `role` VALUES ('3', '校长', '管理整个学校');-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (`id` int(11) NOT NULL AUTO_INCREMENT,`username` varchar(32) NOT NULL COMMENT '用户名称',`password` varchar(20) DEFAULT NULL,`birthday` datetime DEFAULT NULL COMMENT '生日',`sex` char(1) DEFAULT NULL COMMENT '性别',`address` varchar(256) DEFAULT NULL COMMENT '地址',PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=49 DEFAULT CHARSET=utf8;-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('41', '张三丰', '111', '2018-02-27 17:47:08', '男', '上海徐汇');
INSERT INTO `user` VALUES ('42', '宋远桥', '111', '2018-03-02 15:09:37', '女', '北京昌平');
INSERT INTO `user` VALUES ('43', '俞莲舟', '111', '2018-03-04 11:34:34', '女', '陕西西安');
INSERT INTO `user` VALUES ('45', '张翠山', '111', '2018-03-04 12:04:06', '男', '山东济南');
INSERT INTO `user` VALUES ('46', '殷梨亭', '111', '2018-03-07 17:37:26', '男', '河北张家口');
INSERT INTO `user` VALUES ('48', '莫声谷', '111', '2018-03-08 11:44:00', '女', '山西太原');-- ----------------------------
-- Table structure for user_role
-- ----------------------------
DROP TABLE IF EXISTS `user_role`;
CREATE TABLE `user_role` (`id` int(11) NOT NULL AUTO_INCREMENT,`uid` int(11) DEFAULT NULL,`rid` int(11) DEFAULT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;-- ----------------------------
-- Records of user_role
-- ----------------------------
INSERT INTO `user_role` VALUES ('1', '45', '1');
INSERT INTO `user_role` VALUES ('2', '41', '1');
INSERT INTO `user_role` VALUES ('3', '45', '2');
准备工作完成后,开始功能的开发:
1.一对一的关联查询
需求:现在有两张表,根据account表中的uid和user表中的id,将这两张表结合起来查询,并返回数据。
根据需求我们,开始开发:
(1)AccountMapper.java中添加一个方法:
Account findAll(Integer id);
(2)在AccountMapper.xml文件中映射相应的方法:
<resultMap id="findAllResultMap" type="account"><id column="id" property="id"></id><result column="uid" property="uid"></result><result column="money" property="money"></result><association property="user" javaType="user"><id column="id" property="id"></id><result column="username" property="username"></result><result column="birthday" property="birthday"></result><result column="sex" property="sex"></result><result column="address" property="address"></result></association></resultMap><select id="findAll" resultMap="findAllResultMap">select a.id aid ,a.uid uid,a.money money ,u.* from account a left join user u on a.uid=u.id where a.id=#{id};</select>
(3)测试类:添加这个方法
@Testpublic void findAccountById(){AccountMapper accountMapper = sqlSession.getMapper(AccountMapper.class);Account account = accountMapper.findAll(2);System.out.println(account);}
(4)结果展示:
2.一对多关联查询(一个用户可以有多个账户)
(1)首先应该在User Mapper.java文件中添加一个方法。
package com.by.mapper;import com.by.pojo.User;import java.util.List;/*** <p>Project: mybatis - UserMapper</p>* <p>Powered by scl On 2023-12-22 15:52:05</p>* <p>描述:<p>** @author 孙臣龙 [1846080280@qq.com]* @version 1.0* @since 17*/
public interface UserMapper {/*** 一对多*/List<User> findAllUserAccount(Integer id);
}
(2)在UserMapper.xml文件在实现这个方法。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.by.mapper.UserMapper"><resultMap id="findAllResultMap" type="user"><id column="id" property="id"></id><result column="username" property="username"></result><result column="birthday" property="birthday"></result><result column="sex" property="sex"></result><result column="address" property="address"></result><collection property="accountList" ofType="account"><id column="aid" property="id"></id><result column="uid" property="uid"></result><result column="money" property="money"></result></collection></resultMap><select id="findAllUserAccount" parameterType="int" resultMap="findAllResultMap">select a.id aid, a.uid uid, a.money money, u.*from user uleft join account a on u.id=a.uidwhere u.id=#{id}</select>
</mapper>
(3)在User实体类中添加List<Account> accountList;并重写toString方法。
private List<Account> accountList;public List<Account> getAccountList() {return accountList;}public void setAccountList(List<Account> accountList) {this.accountList = accountList;}
(4)编写测试类:
/** Copyright (c) 2020, 2023, All rights reserved.**/
package com.by;import com.by.mapper.AccountMapper;
import com.by.mapper.RoleMapper;
import com.by.mapper.UserMapper;
import com.by.pojo.Role;
import com.by.pojo.User;
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.After;
import org.junit.Before;
import org.junit.Test;import java.io.IOException;
import java.io.InputStream;
import java.util.List;/*** <p>Project: mybatis - MyBatisTest</p>* <p>Powered by scl On 2023-12-18 11:44:53</p>* <p>描述:<p>** @author 孙臣龙 [1846080280@qq.com]* @version 1.0* @since 17*/
public class MyBatisTestRole {private InputStream inputStream;private SqlSession sqlSession;@Beforepublic void init() throws IOException {// 加载配置文件String resource = "mybatis-config.xml";inputStream = Resources.getResourceAsStream(resource);// 创建sqlSessionFActorySqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);// 获得数据的绘画实例sqlSession = sessionFactory.openSession();}/*** 一对多,查询一个用户名下有几张卡*/@Testpublic void findAllUserAccount() {UserMapper userMapper = sqlSession.getMapper(UserMapper.class);List<User> allUserAccount = userMapper.findAllUserAccount(41);for (User user : allUserAccount) {System.out.println(user);}}@Afterpublic void close() throws IOException {inputStream.close();sqlSession.close();}}
(5)结果展示:
3.多对多关联查询(查询角色及角色赋予的用户信息 )
(1)RoleMapper接口中定义一个方法:
package com.by.mapper;import com.by.pojo.Role;
import com.by.pojo.User;import java.util.List;/*** <p>Project: mybatis - RoleMapper</p>* <p>Powered by scl On 2023-12-20 14:37:16</p>* <p>描述:<p>** @author 孙臣龙 [1846080280@qq.com]* @version 1.0* @since 17*/
public interface RoleMapper {List<Role> findAllRoleByUser(Integer id);
}
(2)在RoleMapper.xml文件中实现这个方法。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.by.mapper.RoleMapper"><resultMap id="findAllRoleByUserResult" type="role"><id column="rid" property="id"></id><result column="role_name" property="roleName"></result><result column="role_desc" property="roleDesc"></result><collection property="userList" ofType="user"><id column="id" property="id"></id><result column="username" property="username"></result><result column="address" property="address"></result><result column="sex" property="sex"></result><result column="birthday" property="birthday"></result></collection></resultMap><select id="findAllRoleByUser" parameterType="int" resultMap="findAllRoleByUserResult">select * from role r ,user_role ur,user uwhere ur.rid=r.id and ur.uid=u.id and u.id=#{id}</select>
</mapper>
(3)实体类Role:
/** Copyright (c) 2020, 2023, All rights reserved.**/
package com.by.pojo;import java.util.List;/*** <p>Project: mybatis - Role</p>* <p>Powered by scl On 2023-12-20 14:36:04</p>* <p>描述:<p>** @author 孙臣龙 [1846080280@qq.com]* @version 1.0* @since 17*/
public class Role {private int id;private String roleName;private String roleDesc;private List<User> userList;public List<User> getUserList() {return userList;}public void setUserList(List<User> userList) {this.userList = userList;}@Overridepublic String toString() {return "Role{" +"id=" + id +", roleName='" + roleName + '\'' +", roleDesc='" + roleDesc + '\'' +", userList=" + userList +'}';}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getRoleName() {return roleName;}public void setRoleName(String roleName) {this.roleName = roleName;}public String getRoleDesc() {return roleDesc;}public void setRoleDesc(String roleDesc) {this.roleDesc = roleDesc;}
}
(4)测试类:
/** Copyright (c) 2020, 2023, All rights reserved.**/
package com.by;import com.by.mapper.AccountMapper;
import com.by.mapper.RoleMapper;
import com.by.mapper.UserMapper;
import com.by.pojo.Role;
import com.by.pojo.User;
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.After;
import org.junit.Before;
import org.junit.Test;import java.io.IOException;
import java.io.InputStream;
import java.util.List;/*** <p>Project: mybatis - MyBatisTest</p>* <p>Powered by scl On 2023-12-18 11:44:53</p>* <p>描述:<p>** @author 孙臣龙 [1846080280@qq.com]* @version 1.0* @since 17*/
public class MyBatisTestRole {private InputStream inputStream;private SqlSession sqlSession;@Beforepublic void init() throws IOException {// 加载配置文件String resource = "mybatis-config.xml";inputStream = Resources.getResourceAsStream(resource);// 创建sqlSessionFActorySqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);// 获得数据的绘画实例sqlSession = sessionFactory.openSession();}/*** 多对多:一个人对应多个身份,一个身份包含不同的人** @throws IOException*/@Testpublic void findAllRoleByUser() {RoleMapper roleMapper = sqlSession.getMapper(RoleMapper.class);List<Role> allRoleByUser = roleMapper.findAllRoleByUser(45);for (Role role : allRoleByUser) {System.out.println(role);}}@Afterpublic void close() throws IOException {inputStream.close();sqlSession.close();}}
(5)结果展示: