MyBatis "Set nested Query" and "set nested result" two methods to implement database one-to-many relationship

Source: Internet
Author: User
Tags config

The two entity classes are as follows: User class and goods commodity class. One user corresponds to multiple items (a pair of 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;
	The public void setaddress (String address) {this.address = address;
		Public User () {super (); TODO auto-generated Constructor stub} @Override public String toString () {return ' User [id= ' + ID + ', username= "+ Username +", age= "+ Age +", address="+ Address +", goodslist= "+ goodslist +"] ";

 }
	
	
	
	
	
}
Goods commodity category

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 mapping file for user entity class: Userdao.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" > <map Per namespace= "Com.leo.mapper.UserDao" > <resultmap type= "User" id= "UserMap" > <id column= "u_id" Propert
			y= "id"/> <result column= "username" property= "username"/> <result column= "age" property= "age"/> <result column= "Address" property= "Address"/> <!--when the relationship between tables is a couple of long, collection--> <!--here column= "u_id" is to pass parameters to the nested query select= "..."-<collection property= "goodslist" oftype= "Goods" column=													
		Com.leo.mapper.GoodsDao.selectGoodsForUser "/> </resultMap> <!--goodslist is a collection of private properties in the user entity class-- <select id= "Getuserinfobyid" parametertype= "int" resultmap= "UserMap" > select U.id as u_id, u.u
		Sername, U.age, u.address from user u where u.id =${value};
	</select></mapper>  

Goods Mapper mapping file for entity classes: Goodsdao.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" >
	<!--that's the nested query map--   
	<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>  


Mabatis Environment configuration file Mabatis-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> <!--I put the contents of the data source in the Db.properties file--<properties resource= "com/leo/resources/  Db.properties "/> <!--start-type aliases: Take an alias for Resulttype in Mapper.xml and look 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 "/> & Lt;datasource type= "Pooled" > <property name= "Driver" value= "${driverclass}"/><!--data Source Configuration--&G 
               T <property name= "url" value= "${url}"/> <property name= "UsernAme "value=" ${username} "/> <property name=" password "value=" ${password} "/> </d   
    
    Atasource> </environment> </environments> <!--end-environments configuration--
        <!--Map file resources connected to the entity class-<mappers> <mapper resource= "Com/leo/entity/userdao.xml"/> <mapper resource= "Com/leo/entity/goodsdao.xml"/> </mappers> </configuration>
Test servlet (can also be tested with the main function)

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 {in PUtstream 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 collection of nested queries, there is also a way to set nested results, this way only requires an entity class file, it is a cascade query, automatic completion of the

Here's how to nest the results in a collection:

Just need to change userdao.xml, and just use this one mapping file can complete

<?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" > <map Per namespace= "Com.leo.mapper.UserDao" > <resultmap type= "Goods" id= "Goodsmap" > <id column= "g_id" PR operty= "id"/> <result column= "goodsname" property= "Goodsname"/> <result column= "GoodsNumber" property= "G Oodsnumber "/> <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 ways here, your own analysis can know--</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 connection query, and the nested query uses two times-- 
				G.goodsname, G.goodsnumber, g.user_id from the user U inner join goods g on u.id = g.user_id where
		U.id =${value};   </select> </mapper>


Hope can help everyone, what wording is not correct, hope to be corrected, hope progress


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.