物流案例 网站莱芜要出大事

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,一经查实,立即删除!

相关文章

广州电子商城网站seo优化排名易下拉软件

连接断开阶段 四次挥手机制:TCP连接的断开需要四次挥手,这是因为双方都需要独立地关闭数据传输。第二次和第三次挥手不能合并,因为在回复第二次挥手的时候,可能还有数据没有接收完成,所以需要先回复ACK报文&#xff0c…

创意设计师个人网站wordpress 编辑器 国外

“摘要”式认证( Digestauthentication)是一个简单的认证机制,最初是为HTTP协议开发的,因而也常叫做HTTP摘要,在RFC2671中描述。其身份验证机制很简单,它采用杂凑式(hash)加密方法&a…

免费下载网站模板筑梦网站建设

给你一个整数数组 nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k 个数字。滑动窗口每次只向右移动一位。返回 滑动窗口中的最大值 。示例 1:输入:nums [1,3,-1,-3,5,3,6,7], k 3 输出&am…

如何使用C语言实现Vigenre密码加解密

如何使用C语言实现Vigenre密码加解密 在洛谷看到这题,觉得有意思,遂写。 参考文章:C语言实现Vigenere加解密算法(附带源码) 1. Vigenre密码简介与原理 Vigenre密码是一种多表密码,使用一系列凯撒密码(Caesar ci…

如何给网站加关键词wordpress国外社交插件

这一节继续了解 openmax 目录下的内容。 1、OMX_Core.h 1.1、OMX_BUFFERHEADERTYPE 这是一个比较关键的结构体,上层ACodec/MediaCodec用到的 buffer id、OMXNode 与 OMX component 进行 buffer 传递都是通过该结构体完成,这里将会初步了解结构体中的部…

嵌入式硬件工程师每日提问 - 指南

pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", "Monaco", "Courier New", …

网站点击软件排名北京设计公司logo

样例输入 3 2 2 1 3 1 2样例输出 3 2样例说明 输入的数组为:【3,1,2】 增量序列为:【2,1】 当增量 h2:对于每一个索引 i,我们会将数组元素 arr[i] 与 arr[i−h] 进行比较,并进行可…

网站还建设 域名可以备案吗太原网络推广公司

文章目录 1. 生成模型与判别模型1.1 生成模型 2. VAE3. GAN3.1 GAN-生成对抗网络3.2 GAN-生成对抗网络的训练3.2.1 判别模型的训练:3.2.2 生成网络的训练: 4. LeakyReLU5. GAN代码实例 1. 生成模型与判别模型 生成模型与判别模型 我们前面几章主要介绍了…

安徽网站开发建设泸州网站公司

java编程语言是目前世界最流行的编程语言,它是在c的基础上开发出来的语言,它取其精华去其糟粕让java语言具有功能强大和简单易用的特征。java具有:面对对象、分布式、健壮性、安全性、平台独立与可移植性、多线程、动态性等特点。java可以编写…

信息化和网站建设管理工作情况建立网站视频教程

在做一个网站时,发现视频文件,比如flv,MP4格式在本地可以正常的播放,但是传到了开发机器上,就不行了。播放器的文件地址是对的,就是一直没有反应。 经过长时间的实验,发现问题在与iis的设置问题…

深圳正规网站制作哪家公司好solusvm做网站

昨晚上这个新闻很多人转,但是可能很少有人知道他的链接出处,链接来自于http://www.mohrss.gov.cn/SYrlzyhshbzb/jiuye/gzdt/202108/t20210816_420736.html我记得我还在上小学的时候,我们家有干不完的农活,暑假每天都要下田干活&am…

用什么程序做资讯类网站做网站要准备

0.前提 1. (C)Why did you include the header file of the message file instead of the message file itself?(为包含消息的头文件而不是消息本身?) 回答:msg文件是描述ROS消息字段的文本文件,用于生成不同语言消息…

昆明网站多端小程序设计百度一下官网首页百度

航海日志:Docker的奇幻漂流 欢迎各位探险家们,今天我们将启航进入一个由容器构成的神秘海域——Docker。在这个由代码构建的奇妙世界里,我们将学习如何驾驭这些名为“容器”的神奇船只。准备好了吗?让我们扬帆起航,探…

网站优化自己做该怎么做4虎最新ip是多少呢有人知道吗

1月17日,首届阿里云PolarDB开发者大会在京举办,中国首款自研云原生数据库PolarDB发布“三层分离”全新版本,基于智能决策实现查询性能10倍提升、节省50%成本。面向开发者,阿里云全新推出数据库场景体验馆、训练营等系列新举措&…

【F#学习】列表 List

F#中的列表list是不可变的一列数据。列表中的数据必须具有相同的数据类型。任何试图对列表进行修改的函数或者运算符,实际上都是构建了一个新的列表。 用如下方式来定义一个列表: let empty = [] let singleValue = …

Trae与Gitee MCP深度集成:AI编程工具链迎来重大升级

Trae与Gitee MCP深度集成:AI编程工具链迎来重大升级 在AI技术持续渗透软件开发领域的当下,国内AI编程工具生态迎来重要里程碑。字节跳动旗下明星产品Trae AI IDE与Gitee MCP近日宣布完成深度集成,这一强强联合将为开…

【2025-09-22】加班感悟

20:00培养对小事的耐心,你才能对大事保持耐心。——凯文凯利连续加班了两天,有同事顶不住要休假了。其实,我也要休息一天,但早上要送孩子上学,起床了就睡不回去。尚象也只是对着手机,还要远程限进二生工作进度。…

网站建设公司如何发展python做笔记的网站

前言 在实际开发项目中,我们的工程目录往往是多个app在一个工程下的,每次打包都需要手动的用studio点击Build->Generate Signed Bundle or APK->APK 选择app,签名等,甚至有的app签名还不一样,还需要手动的来回切…

软件开发网站开发学习淘宝导购网站备案

OpenAI⼤模型⽣态并不只有⼀个模型,⽽是提供了涵盖⽂本、代码、对话、语⾳、图像领域的⼀系列模型。 基本介绍 语⾔类⼤模型:GPT-3、GPT-3.5、GPT-4系列模型。并且,OpenAI在训练GPT-3的同时,训练了参数不同、复杂度各不相同的A、…

锋创科技园网站建设最大的建材采购平台

混淆概念的几个说法: 说法1: “以太网交换机不可以实现采用不同网络层协议的互联” 原因:以太网交换机是数据链路层的设备,不懂网络层的知识 说法2: “网桥可互联不同的物理层、不同的MAC子层以及不同速率的以太网”…