Mybatis supports one-to-multiple database relationships by using the "set nested query" and "set nested result" methods.

Source: Internet
Author: User

Mybatis supports one-to-multiple database relationships by using the "set nested query" and "set nested result" methods.

The two entity classes are as follows: User class and Goods Commodity class. One user corresponds to multiple products (one to multiple)

package com.leo.entity;import java.util.List;public class User {private Integer id;private String username;private Integer age;private String address;private List<Goods> goodsList;public List<Goods> getGoodsList() {return goodsList;}public void setGoodsList(List<Goods> goodsList) {this.goodsList = goodsList;}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 Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public String getAddress() {return address;}public void setAddress(String address) {this.address = address;}public User() {super();// TODO Auto-generated constructor stub}@Overridepublic String toString() {return "User [id=" + id + ", username=" + username + ", age=" + age+ ", address=" + address + ", goodsList=" + goodsList + "]";}}
Goods Product

package com.leo.entity;public class Goods {private Integer id;private String goodsName;private Integer goodsNumber;private Integer user_id;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getGoodsName() {return goodsName;}public void setGoodsName(String goodsName) {this.goodsName = goodsName;}public Integer getGoodsNumber() {return goodsNumber;}public void setGoodsNumber(Integer goodsNumber) {this.goodsNumber = goodsNumber;}public Integer getUser_id() {return user_id;}public void setUser_id(Integer user_id) {this.user_id = user_id;}}

Mapper ing file of the User object class: UserDao. xml

<? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE mapper PUBLIC "-// mybatis.org//DTD Mapper 3.0 //" http://mybatis.org/dtd/mybatis-3-mapper.dtd "> <mapper namespace =" com. leo. mapper. userDao "> <resultMap type =" User "id =" userMap "> <id column =" u_id "property =" id "/> <result column =" username "property =" username "/> <result column =" age "property =" age "/> <result column =" address "property =" address "/> <! -- When the relationship between tables is one-to-many, use collection --> <! -- Column = "u_id" here is used to pass parameters to the nested query select = "..... "--> <collection property =" goodsList "ofType =" Goods "column =" u_id "select =" com. leo. mapper. goodsDao. selectGoodsForUser "/> </resultMap> <! -- GoodsList is a set of private properties in the User object class --> <select id = "getUserinfoById" parameterType = "int" resultMap = "userMap"> select u. id as u_id, u. username, u. age, u. address fromuser u where u. id =$ {value }; </select> </mapper>

Mapper ing file of Goods object class: GoodsDao. xml

<? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE mapper PUBLIC "-// mybatis.org//DTD Mapper 3.0 //" http://mybatis.org/dtd/mybatis-3-mapper.dtd "> <! -- This is the nested query ing --> <mapper namespace = "com. leo. mapper. goodsDao "> <select id =" selectGoodsForUser "parameterType =" int "resultType =" Goods "> SELECT id, goodsName, goodsNumber, user_id FROM Goods WHERE user_id =#{ value} </select> </mapper>


Environment profile mabatis-config.xml for mabatis
<? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE configuration PUBLIC "-// mybatis.org//DTD Config 3.0 //" http://mybatis.org/dtd/mybatis-3-config.dtd "> <configuration> <! -- I put the data source content in the db. properties file --> <properties resource = "com/leo/resources/db. properties"/> <! -- Start-type alias: mapper. the resultType in xml gets an alias, which is not very redundant --> <typeAliases> <typeAlias alias = "User" type = "com. leo. entity. user "/> <typeAlias alias =" Goods "type =" com. leo. entity. goods "/> </typeAliases> <! -- End-type alias --> <! -- Start-environments configuration --> <environments default = "development"> <environment id = "development"> <transactionManager type = "JDBC"/> <dataSource type = "POOLED"> <property name = "driver" value = "$ {driverClass}"/> <! -- Data source configuration --> <property name = "url" value = "$ {url}"/> <property name = "username" value = "$ {username}"/> <property name = "password" value = "$ {password}"/> </dataSource> </environment> </environments> <! -- End-environments configuration --> <! -- Connect to the ing file resource of the object class --> <mappers> <mapper resource = "com/leo/entity/UserDao. xml "/> <mapper resource =" com/leo/entity/GoodsDao. xml "/> </mappers> </configuration>
Tested servlet (you can also use the main function for testing)

package com.leo.servlet;import java.io.IOException;import java.io.InputStream;import java.util.List;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.ResultHandler;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;import com.leo.entity.Goods;import com.leo.entity.User;import com.leo.mapper.GoodsDao;import com.leo.mapper.UserDao;/** * Servlet implementation class MybatisServlet */@WebServlet("/MybatisServlet")public class MybatisServlet extends HttpServlet {private static final long serialVersionUID = 1L;protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {InputStream is = Resources.getResourceAsStream("com/leo/resources/mybatis-config.xml");SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);SqlSession session = factory.openSession();//UserDao ud = session.getMapper(UserDao.class);GoodsDao gd = session.getMapper(GoodsDao.class);List<Goods> goodsList= gd.selectGoodsForUser(1);//User user = ud.getUserinfoById(1);//System.out.println(user);//List<Goods> goodsList  =  user.getGoodsList();for (Goods goods : goodsList) {System.out.println(goods.getId()+"   "+ goods.getGoodsName()+"   "+goods.getGoodsNumber()+ "  "+ goods.getUser_id());}session.commit();session.close();}protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet(request, response);}}

The above is a set nested query, and another method is the set nested results. This method only requires one object class file, which is a cascade query that is automatically completed.

The following method uses the nested result of the Set:

You only need to modify UserDao. xml and use this ing file.

<? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE mapper PUBLIC "-// mybatis.org//DTD Mapper 3.0 //" http://mybatis.org/dtd/mybatis-3-mapper.dtd "> <mapper namespace =" com. leo. mapper. userDao "> <resultMap type =" Goods "id =" goodsMap "> <id column =" g_id "property =" id "/> <result column =" goodsName "property =" goodsName "/> <result column =" goodsNumber "property =" goodsNumber "/> <result column =" user_id "property =" user_id "/> </resultMap> <resultMap type = "User" Id = "userMap"> <id column = "u_id" property = "id"/> <result column = "username" property = "username"/> <result column = "age "property =" age "/> <result column =" address "property =" address "/> <collection property =" goodsList "ofType =" Goods "resultMap =" goodsMap "/> <! -- The difference between the two methods is here, you can find out by yourself --> </resultMap> <select id = "getUserinfoById" parameterType = "int" resultMap = "userMap"> select u. id as u_id, u. username, u. age, u. address, g. id as g_id, <! -- Nested results This method uses a join query, while nested query uses two --> g. goodsName, g. goodsNumber, g. user_id fromuser uinner join goods g on u. id = g. user_id where u. id =$ {value }; </select> </mapper>


I hope this will help you. If you have any incorrect wording, I hope you can correct it and make progress.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.