一对一关系
订单与用户:一对一关系
数据库表
-- 数据库db2
-- 主表
CREATE TABLE user (
id INT PRIMARY KEY,
userName VARCHAR ( 50 ),
passWord VARCHAR ( 50 ),
birthday VARCHAR ( 50 ) )
-- 从表
CREATE TABLE orders (
id INT PRIMARY KEY,
ordertime VARCHAR ( 50 ),
total DOUBLE,
uid INT ( 50 ) ,
CONSTRAINT orders FOREIGN KEY (uid) REFERENCES user(id)
)
INSERT INTO `user` VALUES ('1', 'lucy', '123', '2018-12-12');
INSERT INTO `user` VALUES ('2', 'haohao', '123', '2019-12-12');
INSERT INTO `orders` VALUES ('1', '2018-12-12', '3000', '1');
INSERT INTO `orders` VALUES ('2', '2018-12-12', '4000', '1');
INSERT INTO `orders` VALUES ('3', '2018-12-12', '5000', '2');
SELECT * FROM user,orders where user.id = orders.uid;
实现代码
pom.xml (不变)
<?xml version="1.0" encoding="UTF-8"?>
<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>
<groupId>org.example</groupId>
<artifactId>itheima_mybatis_multi</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.32</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!--分页标签-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.2</version>
</dependency>
<dependency>
<groupId>com.github.jsqlparser</groupId>
<artifactId>jsqlparser</artifactId>
<version>1.0</version>
</dependency>
</dependencies>
</project>
jdbc.properties (改数据库)
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db2
jdbc.username=root
jdbc.password=root
log4j.properties (不变)
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=c:/mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### set log levels - for more verbose logging change 'info' to 'debug' ###
log4j.rootLogger=debug, stdout
实体类
注意:Orders 封装了User
package li.chen.com.business.entity;
import java.util.Date;
public class User {
private Integer id;
private String userName;
private String passWord;
private Date birthday;
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 String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", userName='" + userName + '\'' +
", passWord='" + passWord + '\'' +
", birthday=" + birthday +
'}';
}
}
package li.chen.com.business.entity;
import java.util.Date;
public class Orders {
private Integer id;
private Date orderTime;
private Double total;
//当前订单属于哪个用户 即数据库中uid
private User user;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Date getOrderTime() {
return orderTime;
}
public void setOrderTime(Date orderTime) {
this.orderTime = orderTime;
}
public Double getTotal() {
return total;
}
public void setTotal(Double total) {
this.total = total;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
@Override
public String toString() {
return "Orders{" +
"id=" + id +
", orderTime=" + orderTime +
", total=" + total +
", user=" + user +
'}';
}
}
接口
package li.chen.com.business.mapper;
import li.chen.com.business.entity.User;
import java.util.List;
public interface UserMapper {
public List<User> findAll();
}
package li.chen.com.business.mapper;
import li.chen.com.business.entity.Orders;
import java.util.List;
public interface OrdersMapper {
public List<Orders> findAll();
}
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>
<!--加载外部properties-->
<properties resource="jdbc.properties"></properties>
<!--自定义别名-->
<typeAliases>
<typeAlias type="li.chen.com.business.entity.User" alias="user"></typeAlias>
<typeAlias type="li.chen.com.business.entity.Orders" alias="orders"></typeAlias>
</typeAliases>
<!--配置分页助手插件-->
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<!--
告诉分页插件是哪个数据库
但是 配置此行运行会报错
<property name="dialect" value="mysql"/>
-->
</plugin>
</plugins>
<!--配置数据源环境-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!--加载映射文件-->
<mappers>
<mapper resource="li.chen.com.mapper\UserMapper.xml"/>
<mapper resource="li.chen.com.mapper\OrdersMapper.xml"/>
</mappers>
</configuration>
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">
<mapper namespace="li.chen.com.business.mapper.UserMapper">
<select id="findAll" resultType="user">
select * from user;
</select>
</mapper>
OrderMapper.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="li.chen.com.business.mapper.OrdersMapper">
<resultMap id="orderMap" type="orders">
<!--手动指定字段与实体属性的映射关系
column:数据库表的字段名称
property:实体的属性名称
-->
<id column="id" property="id"></id>
<result column="orderTime" property="orderTime"></result>
<result column="total" property="total"></result>
<result column="uid" property="user.id"></result>
<result column="userName" property="user.userName"></result>
<result column="passWord" property="user.passWord"></result>
<result column="birthday" property="user.birthday"></result>
<!--手动指定字段与实体属性的映射关系 (等同于 property="user.id" 那部分配置)
property:当前实体(orders)中的属性名称(private User user)
javaType:当前实体(orders)中的属性类型(User)
-->
<!-- <association property="user" javaType="user">-->
<!-- <id column="uid" property="id"></id>-->
<!-- <result column="userName" property="userName"></result>-->
<!-- <result column="passWord" property="passWord"></result>-->
<!-- <result column="birthday" property="birthday"></result>-->
<!-- </association>-->
</resultMap>
<select id="findAll" resultMap="orderMap">
select * from orders o,user u where o.uid=u.id
</select>
</mapper>
测试类
package li.chen.com.test;
import li.chen.com.business.entity.Orders;
import li.chen.com.business.mapper.OrdersMapper;
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.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class MybatisTest {
@Test
public void test() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
OrdersMapper mapper = sqlSession.getMapper(OrdersMapper.class);
List<Orders> ordersList = mapper.findAll();
for (Orders orders : ordersList) {
System.out.println(orders);
}
}
}
//------------------------------------
11:45:22,532 DEBUG findAll:159 - ==> Preparing: select * from orders o,user u where o.uid=u.id
11:45:22,560 DEBUG findAll:159 - ==> Parameters:
11:45:22,590 DEBUG findAll:159 - <== Total: 3
Orders{id=1, orderTime=Wed Dec 12 00:00:00 CST 2018, total=3000.0, user=User{id=1, userName='lucy', passWord='123', birthday=Wed Dec 12 00:00:00 CST 2018}}
Orders{id=2, orderTime=Wed Dec 12 00:00:00 CST 2018, total=4000.0, user=User{id=1, userName='lucy', passWord='123', birthday=Wed Dec 12 00:00:00 CST 2018}}
Orders{id=3, orderTime=Wed Dec 12 00:00:00 CST 2018, total=5000.0, user=User{id=2, userName='haohao', passWord='123', birthday=Thu Dec 12 00:00:00 CST 2019}}
一对多关系
用户表和订单表的关系为,一个用户有多个订单,一个订单只从属于一个用户
一对多查询的需求:查询一个用户,与此同时查询出该用户具有的订单
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-rFhiSTlV-1610714017436)(E:\my_projest\java基础\msg\image-20210113132320569.png)]
实现代码
User
package li.chen.com.business.entity;
import java.util.Date;
import java.util.List;
public class User {
private Integer id;
private String userName;
private String passWord;
private Date birthday;
//描述的是当前用户存在哪些订单
private List<Orders> ordersList;
public List<Orders> getOrdersList() {
return ordersList;
}
public void setOrdersList(List<Orders> ordersList) {
this.ordersList = ordersList;
}
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 String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", userName='" + userName + '\'' +
", passWord='" + passWord + '\'' +
", birthday=" + birthday +
", ordersList=" + ordersList +
'}';
}
}
UserMapper
package li.chen.com.business.mapper;
import li.chen.com.business.entity.User;
import java.util.List;
public interface UserMapper {
public List<User> findAll();
}
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">
<mapper namespace="li.chen.com.business.mapper.UserMapper">
<resultMap id="userMap" type="user">
<result column="id" property="id"></result>
<result column="userName" property="userName"></result>
<result column="passWord" property="passWord"></result>
<result column="birthday" property="birthday"></result>
<!--配置集合
property:集合名称 >> private List<Orders> ordersList;
ofType:d当前集合中的数据类型 Orders
-->
<collection property="ordersList" ofType="orders">
<!--封装orders数据-->
<result column="uid" property="id"></result>
<result column="orderTime" property="orderTime"></result>
<result column="total" property="total"></result>
</collection>
</resultMap>
<select id="findAll" resultMap="userMap">
select *,o.id oid from user u left join orders o on u.id=o.uid
</select>
</mapper>
测试类
javapackage li.chen.com.test;
import li.chen.com.business.entity.Orders;
import li.chen.com.business.entity.User;
import li.chen.com.business.mapper.OrdersMapper;
import li.chen.com.business.mapper.UserMapper;
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.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class MybatisTest {
@Test
public void test2() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.findAll();
for (User user : userList) {
System.out.println(user);
}
}
}
//---------------------
12:46:33,138 DEBUG findAll:159 - ==> Preparing: select *,o.id oid from user u left join orders o on u.id=o.uid
12:46:33,169 DEBUG findAll:159 - ==> Parameters:
12:46:33,196 DEBUG findAll:159 - <== Total: 3
User{id=1, userName='lucy', passWord='123', birthday=Wed Dec 12 00:00:00 CST 2018, ordersList=[Orders{id=1, orderTime=Wed Dec 12 00:00:00 CST 2018, total=3000.0, user=null}, Orders{id=1, orderTime=Wed Dec 12 00:00:00 CST 2018, total=4000.0, user=null}]}
User{id=2, userName='haohao', passWord='123', birthday=Thu Dec 12 00:00:00 CST 2019, ordersList=[Orders{id=2, orderTime=Wed Dec 12 00:00:00 CST 2018, total=5000.0, user=null}]}
多对多关系
用户表和角色表的关系为,一个用户有多个角色,一个角色被多个用户使用
多对多查询的需求:查询用户同时查询出该用户的所有角色(其实也是一对多)
实现代码
新增数据库表及数据
-- ----------------------------
-- Table structure for sys_role 角色表
-- ----------------------------
DROP TABLE IF EXISTS `sys_role`;
CREATE TABLE `sys_role` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`roleName` varchar(255) DEFAULT NULL,
`roleDesc` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
INSERT INTO `sys_role` VALUES ('1', 'CTO', 'CTO');
INSERT INTO `sys_role` VALUES ('2', 'COO', 'COO');
-- ----------------------------
-- Table structure for sys_user_role 中间表 用户角色
-- ----------------------------
DROP TABLE IF EXISTS `sys_user_role`;
CREATE TABLE `sys_user_role` (
`userId` int(11) NOT NULL,
`roleId` int(11) NOT NULL,
PRIMARY KEY (`userId`,`roleId`),
KEY `roleId` (`roleId`),
CONSTRAINT `sys_user_role_ibfk_1` FOREIGN KEY (`userid`) REFERENCES `sys_role` (`id`),
CONSTRAINT `sys_user_role_ibfk_2` FOREIGN KEY (`roleid`) REFERENCES `user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `sys_user_role` VALUES ('1', '1');
INSERT INTO `sys_user_role` VALUES ('2', '1');
INSERT INTO `sys_user_role` VALUES ('1', '2');
INSERT INTO `sys_user_role` VALUES ('2', '2');
Role 创建实体
package li.chen.com.business.entity;
public class Role {
private Integer id;
private String roleName;
private String roleDesc;
public Integer getId() {
return id;
}
public void setId(Integer 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;
}
@Override
public String toString() {
return "Role{" +
"id=" + id +
", roleName='" + roleName + '\'' +
", roleDesc='" + roleDesc + '\'' +
'}';
}
}
User (增加ordersList)
package li.chen.com.business.entity;
import java.util.Date;
import java.util.List;
public class User {
private Integer id;
private String userName;
private String passWord;
private Date birthday;
//描述的是当前用户存在哪些订单
private List<Orders> ordersList;
//描述的是当前用户具备哪些角色
private List<Role> roleList;
public List<Role> getRoleList() {
return roleList;
}
public void setRoleList(List<Role> roleList) {
this.roleList = roleList;
}
public List<Orders> getOrdersList() {
return ordersList;
}
public void setOrdersList(List<Orders> ordersList) {
this.ordersList = ordersList;
}
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 String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", userName='" + userName + '\'' +
", passWord='" + passWord + '\'' +
", birthday=" + birthday +
", roleList=" + roleList +
'}';
}
}
UserMapper (增加findUserAndRoleAll)
package li.chen.com.business.mapper;
import li.chen.com.business.entity.User;
import java.util.List;
public interface UserMapper {
public List<User> findAll();
public List<User> findUserAndRoleAll();
}
sqlMapConfig.xml(增加Role别名)
<?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>
<!--加载外部properties-->
<properties resource="jdbc.properties"></properties>
<!--自定义别名-->
<typeAliases>
<typeAlias type="li.chen.com.business.entity.User" alias="user"></typeAlias>
<typeAlias type="li.chen.com.business.entity.Orders" alias="orders"></typeAlias>
<typeAlias type="li.chen.com.business.entity.Role" alias="role"></typeAlias>
</typeAliases>
<!--注册类型处理器-->
<!-- <typeHandlers>-->
<!-- <typeHandler handler="li.chen.com.business.handler.DataTypeHandler"></typeHandler>-->
<!-- </typeHandlers>-->
<!--配置分页助手插件-->
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<!--
告诉分页插件是哪个数据库
但是 配置此行运行会报错
<property name="dialect" value="mysql"/>
-->
</plugin>
</plugins>
<!--配置数据源环境-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!--加载映射文件-->
<mappers>
<mapper resource="li.chen.com.mapper\UserMapper.xml"/>
<mapper resource="li.chen.com.mapper\OrdersMapper.xml"/>
</mappers>
</configuration>
UserMapper.xml (与一对多查询写法一致,仅sql不同)
<?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="li.chen.com.business.mapper.UserMapper">
<resultMap id="userMap" type="user">
<result column="id" property="id"></result>
<result column="userName" property="userName"></result>
<result column="passWord" property="passWord"></result>
<result column="birthday" property="birthday"></result>
<!--配置集合
property:集合名称 >> private List<Orders> ordersList;
ofType:d当前集合中的数据类型 Orders
-->
<collection property="ordersList" ofType="orders">
<!--封装orders数据-->
<result column="uid" property="id"></result>
<result column="orderTime" property="orderTime"></result>
<result column="total" property="total"></result>
</collection>
</resultMap>
<select id="findAll" resultMap="userMap">
select *,o.id oid from user u left join orders o on u.id=o.uid
</select>
<!--###################多对多的需求##########################################-->
<resultMap id="userRoleMap" type="user">
<!--user信息-->
<result column="userId" property="id"></result>
<result column="userName" property="userName"></result>
<result column="passWord" property="passWord"></result>
<result column="birthday" property="birthday"></result>
<!--user内部roleList信息-->
<collection property="roleList" ofType="role">
<id column="roleId" property="id"></id>
<id column="roleName" property="roleName"></id>
<id column="roleDesc" property="roleDesc"></id>
</collection>
</resultMap>
<select id="findUserAndRoleAll" resultMap="userRoleMap">
select * from user u,sys_role r,sys_user_role ur where u.id=ur.userId and r.id = ur.roleId
</select>
</mapper>
测试类
package li.chen.com.test;
import li.chen.com.business.entity.Orders;
import li.chen.com.business.entity.User;
import li.chen.com.business.mapper.OrdersMapper;
import li.chen.com.business.mapper.UserMapper;
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.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class MybatisTest {
@Test
public void test3() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userAndRoleAll = mapper.findUserAndRoleAll();
for (User user : userAndRoleAll) {
System.out.println(user);
}
}
}
//----------------------------
14:19:45,121 DEBUG findUserAndRoleAll:159 - ==> Preparing: select * from user u,sys_role r,sys_user_role ur where u.id=ur.userId and r.id = ur.roleId
14:19:45,158 DEBUG findUserAndRoleAll:159 - ==> Parameters:
14:19:45,197 DEBUG findUserAndRoleAll:159 - <== Total: 4
User{id=1, userName='lucy', passWord='123', birthday=Wed Dec 12 00:00:00 CST 2018, roleList=[Role{id=1, roleName='CTO', roleDesc='CTO'}, Role{id=2, roleName='COO', roleDesc='COO'}]}
User{id=2, userName='haohao', passWord='123', birthday=Thu Dec 12 00:00:00 CST 2019, roleList=[Role{id=1, roleName='CTO', roleDesc='CTO'}, Role{id=2, roleName='COO', roleDesc='COO'}]}