物流案例 网站莱芜要出大事
news/
2025/9/23 12:35:22/
文章来源:
物流案例 网站,莱芜要出大事,电影网站建设报价,wordpress 去掉顶部工具栏MyBatis关联映射
为什么要关联映射
实际开发中#xff0c;对数据库操作常常会涉及多张表#xff0c;所以在OOP中就涉及对象与对象的关联关系。针对多表操作#xff0c;MyBatis提供关联映射。
关联关系概述
一对一#xff1a;A类中定义B类的属性b#xff0c;B类中定义A…MyBatis关联映射
为什么要关联映射
实际开发中对数据库操作常常会涉及多张表所以在OOP中就涉及对象与对象的关联关系。针对多表操作MyBatis提供关联映射。
关联关系概述
一对一A类中定义B类的属性bB类中定义A类属性a。一对多一个A类类型对应多个B类。多对多在A类中定义B的集合B中定义A的集合。
嵌套查询与嵌套结果
嵌套查询是通过执行另外一条SQL映射语句来返回预期复杂类型
嵌套查询是在查询SQL嵌套一个子查询嵌套查询会执行多条SQL语句嵌套查询SQL语句编写相对简单
嵌套结果是使用嵌套结果映射来处理的联合结果子集
嵌套结果是一个嵌套的多表查询SQL嵌套结果只会执行一条复杂的SQL语句嵌套结果SQL语句写起来相对麻烦
对于嵌套查询有一个问题那就是执行多条SQL语句导致性能开销很大。于是就有了MyBatis的延迟加载——fetchType。
实践
创建表
我们还是用之前的账户连接数据库终端命令可以如下
mysql -u db_mybatis -p输入密码敲击回车然后切换数据库到db_mybatis
Windows用户可以用终端或者sqlyog执行下面语句
如果你没有这个数据库请回到前面的章节创建它。
USE db_mybatis;我们要使用一个新的customer表所以把之前项目留下的删除掉
DROP TABLE IF EXISTS customer;重新创建它
CREATE TABLE customer(id int(32) NOT NULL AUTO_INCREMENT,username varchar(50) DEFAULT NULL,jobs varchar(50) DEFAULT NULL,phone varchar(16) DEFAULT NULL,PRIMARY KEY (id)
) ENGINEInnoDB AUTO_INCREMENT3 DEFAULT CHARSETutf8;给这张表插入两条数据方便我们接下来写代码用
INSERT INTO customer(id,username,jobs,phone) VALUES (1,zhangsan,teacher,11111111111),(2,lisi,student,11111111112);创建一张idcard表并设置主键主码为id
如果之前存在请删除
DROP TABLE IF EXISTS idcard;CREATE TABLE idcard(id int(11) NOT NULL AUTO_INCREMENT,code varchar(50) DEFAULT NULL,PRIMARY KEY (id)
) ENGINEInnoDB AUTO_INCREMENT3 DEFAULT CHARSETutf8;同样插入两条数据身份证号是我瞎编的为了防止巧合不一定符合真实格式但长度与现实一样
INSERT INTO idcard(id,code) VALUES(1,37010219800X051118),(2,370203199X09092222);创建persion表并插入数据
DROP TABLE IF EXISTS person;CREATE TABLE person(id int(11) NOT NULL AUTO_INCREMENT,name varchar(50) DEFAULT NULL,age int(11) DEFAULT NULL,card_id int(11) DEFAULT NULL,PRIMARY KEY (id),KEY FK_person (card_id),CONSTRAINT FK_person FOREIGN KEY (card_id) REFERENCES idcard (id)
) ENGINEInnoDB AUTO_INCREMENT3 DEFAULT CHARSETutf8;INSERT INTO person(id,name,age,card_id) values (1,张三,18,1),(2,李四,18,2);创建product表并插入数据
DROP TABLE IF EXISTS product;CREATE TABLE product(id int(11) NOT NULL AUTO_INCREMENT,name varchar(32) DEFAULT NULL,price double DEFAULT NULL,PRIMARY KEY (id)
) ENGINEInnoDB AUTO_INCREMENT3 DEFAULT CHARSETutf8;INSERT INTO product(id,name,price) values (1,笔记本电脑,8888.8),(2,华为手机,6666.6);创建user表并插入数据
DROP TABLE IF EXISTS user;CREATE TABLE user(id int(11) NOT NULL,name varchar(20) DEFAULT NULL,password varchar(20) DEFAULT NULL,PRIMARY KEY (id)
) ENGINEInnoDB DEFAULT CHARSETutf8;INSERT INTO user(id,name,password) values (1,zhangsan,654321),(2,lisi,123456);创建orders表
DROP TABLE IF EXISTS orders;
CREATE TABLE orders(id int(11) NOT NULL AUTO_INCREMENT,number varchar(32) DEFAULT NULL,user_id int(11) DEFAULT NULL,PRIMARY KEY (id),KEY FK_orders (user_id),CONSTRAINT FK_orders FOREIGN KEY (user_id) REFERENCES user (id)
) ENGINEInnoDB AUTO_INCREMENT2 DEFAULT CHARSETutf8;INSERT INTO orders(id,number,user_id) VALUES (1,201901,1);创建orderitem表还是一样如果之前存在先删除。这个表一定放后面否则创建外键会报错。
DROP TABLE IF EXISTS orderitem;CREATE TABLE orderitem(id int(11) NOT NULL AUTO_INCREMENT,orders_id int(11) DEFAULT NULL,product_id int(11) DEFAULT NULL,PRIMARY KEY (id),KEY FK_orderitem (orders_id),KEY FK_orderitem_product (product_id),CONSTRAINT FK_orderitem_product FOREIGN KEY (product_id) REFERENCES product (id),CONSTRAINT FK_orderitem FOREIGN KEY (orders_id) REFERENCES orders (id)
) ENGINEInnoDB AUTO_INCREMENT3 DEFAULT CHARSETutf8;INSERT INTO orderitem(id,orders_id,product_id) VALUES (1,1,1),(2,1,2);构建项目
我们新创建一个Maven项目top.cairbin.test5
pom.xml添加依赖包
project xmlnshttp://maven.apache.org/POM/4.0.0 xmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsdmodelVersion4.0.0/modelVersiongroupIdtop.cairbin/groupIdartifactIdtest5/artifactIdversion0.0.1-SNAPSHOT/versionpackagingjar/packagingnametest5/nameurlhttp://maven.apache.org/urlpropertiesproject.build.sourceEncodingUTF-8/project.build.sourceEncoding/propertiesdependenciesdependencygroupIdjunit/groupIdartifactIdjunit/artifactIdversion4.12/versionscopetest/scope/dependency!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --dependencygroupIdorg.mybatis/groupIdartifactIdmybatis/artifactIdversion3.5.4/version/dependency!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --dependencygroupIdmysql/groupIdartifactIdmysql-connector-java/artifactIdversion8.0.33/version/dependency!-- https://mvnrepository.com/artifact/org.mybatis.generator/mybatis-generator-core --dependencygroupIdorg.mybatis.generator/groupIdartifactIdmybatis-generator-core/artifactIdversion1.4.0/version/dependencydependencygroupIdlog4j/groupIdartifactIdlog4j/artifactIdversion1.2.17/version
/dependency/dependencies
/project创建与src平级的resources目录并右键-Build Path-Use as Source Folder
在里面添加一个数据库配置文件db.properties
jdbc.drivercom.mysql.jdbc.Driver
jdbc.urljdbc:mysql://localhost:3306/db_mybatis
jdbc.usernamedb_mybatis
jdbc.passworddb_mybatis配置MyBatis在同目录下创建mybatis-config.xml这个文件会使用db.properties里面的配置以${...}的方式调用在properties resourcedb.properties /里声明位置。
?xml version1.0 encodingUTF-8 ?
!DOCTYPE configuration PUBLIC -//mybatis.org//DTD Config 3.0//ENhttp://mybatis.org/dtd/mybatis-3-config.dtd
configurationproperties resourcedb.properties /settings!-- 延迟加载的开关 --setting namelazyLoadingEnabled valuefalse /!-- 设置积极加载true或按需加载false --setting nameaggressiveLazyLoading valuetrue /setting namemapUnderscoreToCamelCase valuetrue /setting namelogImpl valueSTDOUT_LOGGING //settingstypeAliasespackage nametop.cairbin.test5 //typeAliases!--1.配置环境 默认的环境id为mysql --environments defaultmysql!--1.2.配置id为mysql的数据库环境 --environment idmysql!-- 使用JDBC的事务管理 --transactionManager typeJDBC /!--数据库连接池 --dataSource typePOOLED!-- 数据库驱动 --property namedriver value${jdbc.driver} /!-- 连接数据库的url --property nameurl value${jdbc.url} /!-- 连接数据库的用户名 --property nameusername value${jdbc.username} /!-- 连接数据库的密码 --property namepassword value${jdbc.password} //dataSource/environment/environments!--2.配置Mapper的位置 --mappersmapper resourcetop/cairbin/test5/mapper/CustomerMapper.xml /mapper resourcetop/cairbin/test5/mapper/UserMapper.xml /mapper resourcetop/cairbin/test5/mapper/IdCardMapper.xml /mapper resourcetop/cairbin/test5/mapper/OrdersMapper.xml /mapper resourcetop/cairbin/test5/mapper/PersonMapper.xml /mapper resourcetop/cairbin/test5/mapper/ProductMapper.xml //mappers
/configuration注意上方的mapper的目录我们一会介绍。
然后添加log4j的配置文件log4j.properties
# Global logging configuration
log4j.rootLoggerERROR, stdout
# MyBatis logging configuration...
log4j.logger.top.cairbin.test5DEBUG
# Console output...
log4j.appender.stdoutorg.apache.log4j.ConsoleAppender
log4j.appender.stdout.layoutorg.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern%5p [%t] - %m%nDao层
我们先把对应的类创建了再说到src/main/java下top.cairbin.test5创建一个子包名称为top.cairbin.test5.dao 在我们新创建的包下面编写若干个类
首先是Person类此时我们的IdCard还没创建IDE提示错误很正常
package top.cairbin.test5.dao;public class Person {private Integer id;private String name;private Integer age;private Integer cardId;private IdCard card;public void setId(Integer id) {this.id id;}public Integer getId() {return this.id;}public void setName(String name) {this.name name;}public String getName() {return this.name;}public void setAge(Integer age) {this.age age;}public Integer getAge() {return this.age;}public Integer getCardId() {return cardId;}public void setCardId(Integer cardId) {this.cardId cardId;}public void setCard(IdCard card) {this.card card;}public IdCard getCard() {return this.card;}
}接下来创建IdCard
package top.cairbin.test5.dao;public class IdCard {private Integer id;private String code;public Integer getId() {return id;}public void setId(Integer id) {this.id id;}public String getCode() {return code;}public void setCode(String code) {this.code code null ? null : code.trim();}
}然后是Customer类
package top.cairbin.test5.dao;public class Customer {private Integer id;private String username;private String jobs;private String phone;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 null ? null : username.trim();}public String getJobs() {return jobs;}public void setJobs(String jobs) {this.jobs jobs null ? null : jobs.trim();}public String getPhone() {return phone;}public void setPhone(String phone) {this.phone phone null ? null : phone.trim();}
}接着是Orders
package top.cairbin.test5.dao;package top.cairbin.test5.dao;import java.util.List;public class Orders {private Integer id;private String number;private Integer userId;private ListProduct productList;public Integer getId() {return id;}public void setId(Integer id) {this.id id;}public String getNumber() {return number;}public void setNumber(String number) {this.number number null ? null : number.trim();}public Integer getUserId() {return userId;}public void setUserId(Integer userId) {this.userId userId;}public void setProductList(ListProduct productList) {this.productList productList;}public ListProduct getProductList(){return this.productList;}
}Product类
package top.cairbin.test5.dao;public class Product {private Integer id;private String name;private Double price;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 null ? null : name.trim();}public Double getPrice() {return price;}public void setPrice(Double price) {this.price price;}
}User类
package top.cairbin.test5.dao;import java.util.List;public class User {private Integer id;private String name;private String password;private ListOrders ordersList;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 null ? null : name.trim();}public String getPassword() {return password;}public void setPassword(String password) {this.password password null ? null : password.trim();}public void setOrdersList(ListOrders ordersList) {this.ordersList ordersList;}public ListOrders getOrdersList(){return this.ordersList;}
}Util层
这一层我们来放置一些工具类。创建包top.cairbin.test5.util
然后在下面创建MyBatisHelper类
package top.cairbin.test5.util;import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MyBatisHelper {private static SqlSessionFactory sqlSessionFactory null;// 初始化SqlSessionFactory对象static {try {// 使用MyBatis提供的Resources类加载MyBatis的配置文件Reader reader Resources.getResourceAsReader(mybatis-config.xml);// 构建SqlSessionFactory工厂sqlSessionFactory new SqlSessionFactoryBuilder().build(reader);} catch (Exception e) {e.printStackTrace();}}// 获取SqlSession对象的静态方法public static SqlSession getSession() {return sqlSessionFactory.openSession();}
}Mapper层
接下来我们再为top.cairbin.test5创建一个子包top.cairbin.test5.mapper该层主要实现数据持久化。
与上面不一样的是我们这里定义的是接口
首先是CustomerMapper接口
package top.cairbin.test5.mapper;import top.cairbin.test5.dao.Customer;public interface CustomerMapper {int deleteByPrimaryKey(Integer id);int insert(Customer record);int insertSelective(Customer record);Customer selectByPrimaryKey(Integer id);int updateByPrimaryKeySelective(Customer record);int updateByPrimaryKey(Customer record);
}到这里你可能会问谁去实现它们呢还记得mybatis-config.xml里那些mapper吗它们每一个都指定resource到Mapper层也就是说我们要在这里写XML文件让MyBatis实现这些方法。
第一个是CustomerMapper.xml注意此处的namespace与resultMap的id下文同理。
?xml version1.0 encodingUTF-8?
!DOCTYPE mapper PUBLIC -//mybatis.org//DTD Mapper 3.0//EN http://mybatis.org/dtd/mybatis-3-mapper.dtd
mapper namespacetop.cairbin.test5.mapper.CustomerMapperresultMap idBaseResultMap typetop.cairbin.test5.dao.Customerid columnid jdbcTypeINTEGER propertyid /result columnusername jdbcTypeVARCHAR propertyusername /result columnjobs jdbcTypeVARCHAR propertyjobs /result columnphone jdbcTypeVARCHAR propertyphone //resultMapsql idBase_Column_Listid, username, jobs, phone/sqlselect idselectByPrimaryKey parameterTypejava.lang.Integer resultMapBaseResultMapselect include refidBase_Column_List /from customerwhere id #{id,jdbcTypeINTEGER}/selectdelete iddeleteByPrimaryKey parameterTypejava.lang.Integerdelete from customerwhere id #{id,jdbcTypeINTEGER}/deleteinsert idinsert parameterTypetop.cairbin.test5.dao.Customerinsert into customer (id, username, jobs, phone)values (#{id,jdbcTypeINTEGER}, #{username,jdbcTypeVARCHAR}, #{jobs,jdbcTypeVARCHAR}, #{phone,jdbcTypeVARCHAR})/insertinsert idinsertSelective parameterTypetop.cairbin.test5.dao.Customerinsert into customertrim prefix( suffix) suffixOverrides,if testid ! nullid,/ifif testusername ! nullusername,/ifif testjobs ! nulljobs,/ifif testphone ! nullphone,/if/trimtrim prefixvalues ( suffix) suffixOverrides,if testid ! null#{id,jdbcTypeINTEGER},/ifif testusername ! null#{username,jdbcTypeVARCHAR},/ifif testjobs ! null#{jobs,jdbcTypeVARCHAR},/ifif testphone ! null#{phone,jdbcTypeVARCHAR},/if/trim/insertupdate idupdateByPrimaryKeySelective parameterTypetop.cairbin.test5.dao.Customerupdate customersetif testusername ! nullusername #{username,jdbcTypeVARCHAR},/ifif testjobs ! nulljobs #{jobs,jdbcTypeVARCHAR},/ifif testphone ! nullphone #{phone,jdbcTypeVARCHAR},/if/setwhere id #{id,jdbcTypeINTEGER}/updateupdate idupdateByPrimaryKey parameterTypetop.cairbin.test5.dao.Customerupdate customerset username #{username,jdbcTypeVARCHAR},jobs #{jobs,jdbcTypeVARCHAR},phone #{phone,jdbcTypeVARCHAR}where id #{id,jdbcTypeINTEGER}/update
/mapper对了请检查你XML中的方法的parameterType属性以及resultType对应类型的包是否正确
然后是IdCardMapper接口
package top.cairbin.test5.mapper;import top.cairbin.test5.dao.IdCard;public interface IdCardMapper {int deleteByPrimaryKey(Integer id);int insert(IdCard record);int insertSelective(IdCard record);IdCard selectByPrimaryKey(Integer id);int updateByPrimaryKeySelective(IdCard record);int updateByPrimaryKey(IdCard record);
}同样在IdCardMapper.xml里实现这些方法
?xml version1.0 encodingUTF-8?
!DOCTYPE mapper PUBLIC -//mybatis.org//DTD Mapper 3.0//EN http://mybatis.org/dtd/mybatis-3-mapper.dtd
mapper namespacetop.cairbin.test5.mapper.IdCardMapperresultMap idBaseResultMap typetop.cairbin.test5.dao.IdCardid columnid jdbcTypeINTEGER propertyid /result columncode jdbcTypeVARCHAR propertycode //resultMapsql idBase_Column_Listid, code/sqlselect idselectByPrimaryKey parameterTypejava.lang.Integer resultMapBaseResultMapselect include refidBase_Column_List /from idcardwhere id #{id,jdbcTypeINTEGER}/selectdelete iddeleteByPrimaryKey parameterTypejava.lang.Integerdelete from idcardwhere id #{id,jdbcTypeINTEGER}/deleteinsert idinsert parameterTypetop.cairbin.test5.dao.IdCardinsert into idcard (id, code)values (#{id,jdbcTypeINTEGER}, #{code,jdbcTypeVARCHAR})/insertinsert idinsertSelective parameterTypetop.cairbin.test5.dao.IdCardinsert into idcardtrim prefix( suffix) suffixOverrides,if testid ! nullid,/ifif testcode ! nullcode,/if/trimtrim prefixvalues ( suffix) suffixOverrides,if testid ! null#{id,jdbcTypeINTEGER},/ifif testcode ! null#{code,jdbcTypeVARCHAR},/if/trim/insertupdate idupdateByPrimaryKeySelective parameterTypetop.cairbin.test5.dao.IdCardupdate idcardsetif testcode ! nullcode #{code,jdbcTypeVARCHAR},/if/setwhere id #{id,jdbcTypeINTEGER}/updateupdate idupdateByPrimaryKey parameterTypetop.cairbin.test5.dao.IdCardupdate idcardset code #{code,jdbcTypeVARCHAR}where id #{id,jdbcTypeINTEGER}/update
/mapper然后是ProductMapper接口以及ProductMapper.xml
package top.cairbin.test5.mapper;
import top.cairbin.test5.dao.Product;public interface ProductMapper {int deleteByPrimaryKey(Integer id);int insert(Product record);int insertSelective(Product record);Product selectByPrimaryKey(Integer id);int updateByPrimaryKeySelective(Product record);int updateByPrimaryKey(Product record);
}?xml version1.0 encodingUTF-8?
!DOCTYPE mapper PUBLIC -//mybatis.org//DTD Mapper 3.0//EN http://mybatis.org/dtd/mybatis-3-mapper.dtd
mapper namespacetop.cairbin.test5.mapper.ProductMapperresultMap idBaseResultMap typetop.cairbin.test5.dao.Productid columnid jdbcTypeINTEGER propertyid /result columnname jdbcTypeVARCHAR propertyname /result columnprice jdbcTypeDOUBLE propertyprice //resultMapsql idBase_Column_Listid, name, price/sqlselect idfindProductByOrderId parameterTypeInteger resultTypeProductSELECT * from product where id IN(SELECT product_id FROM orderitem WHERE orders_id #{id})/selectselect idselectByPrimaryKey parameterTypejava.lang.Integer resultMapBaseResultMapselect include refidBase_Column_List /from productwhere id #{id,jdbcTypeINTEGER}/selectdelete iddeleteByPrimaryKey parameterTypejava.lang.Integerdelete from productwhere id #{id,jdbcTypeINTEGER}/deleteinsert idinsert parameterTypetop.cairbin.test5.dao.Productinsert into product (id, name, price)values (#{id,jdbcTypeINTEGER}, #{name,jdbcTypeVARCHAR}, #{price,jdbcTypeDOUBLE})/insertinsert idinsertSelective parameterTypetop.cairbin.test5.dao.Productinsert into producttrim prefix( suffix) suffixOverrides,if testid ! nullid,/ifif testname ! nullname,/ifif testprice ! nullprice,/if/trimtrim prefixvalues ( suffix) suffixOverrides,if testid ! null#{id,jdbcTypeINTEGER},/ifif testname ! null#{name,jdbcTypeVARCHAR},/ifif testprice ! null#{price,jdbcTypeDOUBLE},/if/trim/insertupdate idupdateByPrimaryKeySelective parameterTypetop.cairbin.test5.dao.Productupdate productsetif testname ! nullname #{name,jdbcTypeVARCHAR},/ifif testprice ! nullprice #{price,jdbcTypeDOUBLE},/if/setwhere id #{id,jdbcTypeINTEGER}/updateupdate idupdateByPrimaryKey parameterTypetop.cairbin.test5.dao.Productupdate productset name #{name,jdbcTypeVARCHAR},price #{price,jdbcTypeDOUBLE}where id #{id,jdbcTypeINTEGER}/update
/mapper对于剩下来的几个Dao层类对应的Mapper需要特别注意下因为它们的类里都包含复合类型这也是我们这一章节真正要学习的东西——关联映射。
PersonMapper接口
package top.cairbin.test5.mapper;import top.cairbin.test5.dao.Person;public interface PersonMapper {int deleteByPrimaryKey(Integer id);int insert(Person record);int insertSelective(Person record);Person selectByPrimaryKey(Integer id);int updateByPrimaryKeySelective(Person record);int updateByPrimaryKey(Person record);
}PersonMapper.xml文件请重点关注findPersonById和findPersonById2这两个地方。
?xml version1.0 encodingUTF-8?
!DOCTYPE mapper PUBLIC -//mybatis.org//DTD Mapper 3.0//EN http://mybatis.org/dtd/mybatis-3-mapper.dtd
mapper namespacetop.cairbin.test5.mapper.PersonMapperresultMap idBaseResultMap typetop.cairbin.test5.dao.Personid columnid jdbcTypeINTEGER propertyid /result columnname jdbcTypeVARCHAR propertyname /result columnage jdbcTypeINTEGER propertyage /result columncard_id jdbcTypeINTEGER propertycardId //resultMapsql idBase_Column_Listid, name, age, card_id/sql!-- 嵌套查询通过执行另外一条SQL映射语句来返回预期的特殊类型 --select idfindPersonById parameterTypeInteger resultMapIdCardWithPersonResultSELECT * from person where id#{id}/selectresultMap typePerson idIdCardWithPersonResultid propertyid columnid /result propertyname columnname /result propertyage columnage /!-- 一对一association使用select属性引入另外一条SQL语句 --association propertycard columncard_id javaTypetop.cairbin.test5.dao.IdCardselecttop.cairbin.test5.mapper.IdCardMapper.selectByPrimaryKey //resultMap!-- 嵌套结果使用嵌套结果映射来处理重复的联合结果的子集 --select idfindPersonById2 parameterTypeInteger resultMapIdCardWithPersonResult2SELECT p.*,idcard.codefrom person p,idcard idcardwhere p.card_ididcard.id and p.id #{id}/selectresultMap typePerson idIdCardWithPersonResult2id propertyid columnid /result propertyname columnname /result propertyage columnage /association propertycard javaTypeIdCardid propertyid columnid /result propertycode columncode //association/resultMapselect idselectByPrimaryKey parameterTypejava.lang.Integer resultMapBaseResultMapselect include refidBase_Column_List /from personwhere id #{id,jdbcTypeINTEGER}/selectdelete iddeleteByPrimaryKey parameterTypejava.lang.Integerdelete from personwhere id #{id,jdbcTypeINTEGER}/deleteinsert idinsert parameterTypetop.cairbin.test5.dao.Personinsert into person (id, name, age, card_id)values (#{id,jdbcTypeINTEGER}, #{name,jdbcTypeVARCHAR}, #{age,jdbcTypeINTEGER}, #{cardId,jdbcTypeINTEGER})/insertinsert idinsertSelective parameterTypetop.cairbin.test5.dao.Personinsert into persontrim prefix( suffix) suffixOverrides,if testid ! nullid,/ifif testname ! nullname,/ifif testage ! nullage,/ifif testcardId ! nullcard_id,/if/trimtrim prefixvalues ( suffix) suffixOverrides,if testid ! null#{id,jdbcTypeINTEGER},/ifif testname ! null#{name,jdbcTypeVARCHAR},/ifif testage ! null#{age,jdbcTypeINTEGER},/ifif testcardId ! null#{cardId,jdbcTypeINTEGER},/if/trim/insertupdate idupdateByPrimaryKeySelective parameterTypetop.cairbin.test5.dao.Personupdate personsetif testname ! nullname #{name,jdbcTypeVARCHAR},/ifif testage ! nullage #{age,jdbcTypeINTEGER},/ifif testcardId ! nullcard_id #{cardId,jdbcTypeINTEGER},/if/setwhere id #{id,jdbcTypeINTEGER}/updateupdate idupdateByPrimaryKey parameterTypetop.cairbin.test5.dao.Personupdate personset name #{name,jdbcTypeVARCHAR},age #{age,jdbcTypeINTEGER},card_id #{cardId,jdbcTypeINTEGER}where id #{id,jdbcTypeINTEGER}/update
/mapper对于上面这么长的文件最重要的地方是这里
!-- 一对一association使用select属性引入另外一条SQL语句 --
association propertycard columncard_id javaTypetop.cairbin.test5.dao.IdCard
selecttop.cairbin.test5.mapper.IdCardMapper.selectByPrimaryKey /为了看到效果我们在mybatis-config.xml里将延迟加载关掉。
settings!-- 延迟加载的开关 --!-- 为了让大家看到关联关系的效果我们在这里关闭了延迟加载 -- setting namelazyLoadingEnabled valuefalse / setting nameaggressiveLazyLoading valuetrue/
/settings创建UserMapper接口和UserMapper.xml
package top.cairbin.test5.mapper;import top.cairbin.test5.dao.User;public interface UserMapper {int deleteByPrimaryKey(Integer id);int insert(User record);int insertSelective(User record);User selectByPrimaryKey(Integer id);int updateByPrimaryKeySelective(User record);int updateByPrimaryKey(User record);
}?xml version1.0 encodingUTF-8?
!DOCTYPE mapper PUBLIC -//mybatis.org//DTD Mapper 3.0//EN http://mybatis.org/dtd/mybatis-3-mapper.dtd
mapper namespacetop.cairbin.test5.mapper.UserMapperresultMap idBaseResultMap typetop.cairbin.test5.dao.Userid columnid jdbcTypeINTEGER propertyid /result columnname jdbcTypeVARCHAR propertyname /result columnpassword jdbcTypeVARCHAR propertypassword /collection propertyordersList columnid ofTypeOrders selecttop.cairbin.test5.mapper.OrdersMapper.findOrdersWithUser/collection/resultMapsql idBase_Column_Listid, name, password/sqlselect idselectByPrimaryKey parameterTypejava.lang.Integer resultMapBaseResultMapselect include refidBase_Column_List /from userwhere id #{id,jdbcTypeINTEGER}/selectdelete iddeleteByPrimaryKey parameterTypejava.lang.Integerdelete from userwhere id #{id,jdbcTypeINTEGER}/deleteinsert idinsert parameterTypetop.cairbin.test5.dao.Userinsert into user (id, name, password)values (#{id,jdbcTypeINTEGER}, #{name,jdbcTypeVARCHAR}, #{password,jdbcTypeVARCHAR})/insertinsert idinsertSelective parameterTypetop.cairbin.test5.dao.Userinsert into usertrim prefix( suffix) suffixOverrides,if testid ! nullid,/ifif testname ! nullname,/ifif testpassword ! nullpassword,/if/trimtrim prefixvalues ( suffix) suffixOverrides,if testid ! null#{id,jdbcTypeINTEGER},/ifif testname ! null#{name,jdbcTypeVARCHAR},/ifif testpassword ! null#{password,jdbcTypeVARCHAR},/if/trim/insertupdate idupdateByPrimaryKeySelective parameterTypetop.cairbin.test5.dao.Userupdate usersetif testname ! nullname #{name,jdbcTypeVARCHAR},/ifif testpassword ! nullpassword #{password,jdbcTypeVARCHAR},/if/setwhere id #{id,jdbcTypeINTEGER}/updateupdate idupdateByPrimaryKey parameterTypetop.cairbin.test5.dao.Userupdate userset name #{name,jdbcTypeVARCHAR},password #{password,jdbcTypeVARCHAR}where id #{id,jdbcTypeINTEGER}/update
/mapper最后OrdersMapper和OrdersMapper.xml
package top.cairbin.test5.mapper;import top.cairbin.test5.dao.Orders;public interface OrdersMapper {int deleteByPrimaryKey(Integer id);int insert(Orders record);int insertSelective(Orders record);Orders selectByPrimaryKey(Integer id);int updateByPrimaryKeySelective(Orders record);int updateByPrimaryKey(Orders record);
}?xml version1.0 encodingUTF-8?
!DOCTYPE mapper PUBLIC -//mybatis.org//DTD Mapper 3.0//EN http://mybatis.org/dtd/mybatis-3-mapper.dtd
mapper namespacetop.cairbin.test5.mapper.OrdersMapperresultMap idBaseResultMap typetop.cairbin.test5.dao.Ordersid columnid jdbcTypeINTEGER propertyid /result columnnumber jdbcTypeVARCHAR propertynumber /result columnuser_id jdbcTypeINTEGER propertyuserId //resultMapsql idBase_Column_Listid, number, user_id/sqlselect idfindOrdersWithUser parameterTypeInteger resultMapBaseResultMapselect * from orders WHERE user_id#{id} /selectselect idselectByPrimaryKey parameterTypejava.lang.Integer resultMapBaseResultMapselect include refidBase_Column_List /from orderswhere id #{id,jdbcTypeINTEGER}/selectdelete iddeleteByPrimaryKey parameterTypejava.lang.Integerdelete from orderswhere id #{id,jdbcTypeINTEGER}/deleteinsert idinsert parameterTypetop.cairbin.test5.dao.Ordersinsert into orders (id, number, user_id)values (#{id,jdbcTypeINTEGER}, #{number,jdbcTypeVARCHAR}, #{userId,jdbcTypeINTEGER})/insertinsert idinsertSelective parameterTypetop.cairbin.test5.dao.Ordersinsert into orderstrim prefix( suffix) suffixOverrides,if testid ! nullid,/ifif testnumber ! nullnumber,/ifif testuserId ! nulluser_id,/if/trimtrim prefixvalues ( suffix) suffixOverrides,if testid ! null#{id,jdbcTypeINTEGER},/ifif testnumber ! null#{number,jdbcTypeVARCHAR},/ifif testuserId ! null#{userId,jdbcTypeINTEGER},/if/trim/insertupdate idupdateByPrimaryKeySelective parameterTypetop.cairbin.test5.dao.Ordersupdate orderssetif testnumber ! nullnumber #{number,jdbcTypeVARCHAR},/ifif testuserId ! nulluser_id #{userId,jdbcTypeINTEGER},/if/setwhere id #{id,jdbcTypeINTEGER}/updateupdate idupdateByPrimaryKey parameterTypetop.cairbin.test5.dao.Ordersupdate ordersset number #{number,jdbcTypeVARCHAR},user_id #{userId,jdbcTypeINTEGER}where id #{id,jdbcTypeINTEGER}/update
/mapper我们编写测试类在src/test/java下的top.cairbin.test5里
PersonTest类来测试一对一的关系
package top.cairbin.test5;import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import top.cairbin.test5.dao.Person;
import top.cairbin.test5.util.*;public class PersonTest {Testpublic void findPersonByIdTest() {// 1、通过工具类生成SqlSession对象SqlSession session MyBatisHelper.getSession();// 2.使用MyBatis嵌套查询的方式查询id为1的人的信息Person person session.selectOne(top.cairbin.test5.mapper. PersonMapper.selectByPrimaryKey, 1);// 3、输出查询结果信息System.out.println(person);// 4、关闭SqlSessionsession.close();}//测试一对一嵌套结果Testpublic void findPersonByIdTest2() {// 1、通过工具类生成SqlSession对象SqlSession session MyBatisHelper.getSession();// 2.使用MyBatis嵌套查询的方式查询id为1的人的信息Person person session.selectOne(top.cairbin.test5.mapper. PersonMapper.findPersonById2, 1);// 3、输出查询结果信息System.out.println(person);// 4、关闭SqlSessionsession.close();}
}点击运行两个方法所用时间差距不小。
我们再编写测试类UserTest来测试一对多
package top.cairbin.test5;import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import top.cairbin.test5.dao.User;
import top.cairbin.test5.util.MyBatisHelper;public class UserTest {Testpublic void findUserTest() {// 1、通过工具类生成SqlSession对象SqlSession session MyBatisHelper.getSession();// 2、查询id为1的用户信息注意包名为mapper层的User user session.selectOne(top.cairbin.test5.mapper. UserMapper.selectByPrimaryKey, 1);// 3、输出查询结果信息System.out.println(user);// 4、关闭SqlSessionsession.close();}}最后编写OrdersTest来测试多对多
package top.cairbin.test5;import org.apache.ibatis.session.SqlSession;
import org.junit.Test;import top.cairbin.test5.dao.Orders;
import top.cairbin.test5.util.MyBatisHelper;public class OrdersTest {Testpublic void findOrdersTest(){// 1、通过工具类生成SqlSession对象SqlSession session MyBatisHelper.getSession();// 2、查询id为1的订单中的商品信息Orders orders session.selectOne(top.cairbin.test5.mapper. OrdersMapper.selectByPrimaryKey, 1);// 3、输出查询结果信息System.out.println(orders);// 4、关闭SqlSessionsession.close();}
}总结
在本章节我们学习了MyBatis的关联映射。此外你会发现我们写代码不再像以前一样只放在一个包里而是创建好几个子包分层放置不同的代码这有利于代码逻辑清晰并且方便维护这种分层设计已经有一个正式项目的雏形了当你写完这些东西的时候项目目录应该与我差不多。
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/912555.shtml
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!