java-mybaits-00502-Case-mapping analysis-pair of one or one-to-many, many-to-many

Source: Internet
Author: User

1, one-on-one query "class attributes can, association" case: query all order information, related to query the next single user information. Note: Because an order information will only be a person under the order, so from the query order information related to query user information for one-on-one query. If you query the user information from the user's order information is a one-to-many query, because one user can place multiple orders. 1.1, method One "Resulttype": Use Resulttype, define order Information Po class, this PO class includes order information and user information: 1.1.1, SQL statements:
SELECT orders. * ,   user. Username,  useraddress  fromuser  WHERE orders. user_id = user. ID
1.1.2, define the Pojo class to map the results of the upper SQL query to Pojo, and all query column names must be included in Pojo. The original Orders.java cannot map all fields and requires a newly created Pojo. Create a Pojo inheritance that includes more query fields than the PO class, as follows:
 PackageCom.lhx.mybatis.po;Importjava.util.Date; Public classOrder {PrivateInteger ID; PrivateString user_id; PrivateDouble number; PrivateString Note; PrivateDate Createtime;  PublicInteger getId () {returnID; }     Public voidsetId (Integer id) { This. ID =ID; }     PublicString getuser_id () {returnuser_id; }     Public voidsetuser_id (String user_id) { This. user_id =user_id; }     PublicDouble GetNumber () {returnNumber ; }     Public voidSetnumber (Double number) { This. Number =Number ; }     PublicString getnote () {returnNote; }     Public voidSetnote (String note) { This. Note =Note; }     PublicDate Getcreatetime () {returnCreatetime; }     Public voidsetcreatetime (Date createtime) { This. Createtime =Createtime; }    }
View Code
 PackageCom.lhx.mybatis.po; Public classOrderscustomextendsOrder {PrivateString username; PrivateString address;  PublicString GetUserName () {returnusername; }     Public voidSetusername (String username) { This. Username =username; }     PublicString getaddress () {returnaddress; }     Public voidsetaddress (String address) { This. Address =address; } @Override PublicString toString () {return"Orderscustom [username=" + Username + ", address=" + address + ", getId () =" +getId ()+ ", getuser_id () =" + getuser_id () + ", getnumber () =" + getnumber () + ", getnote () =" +getnote ()+ ", getcreatetime () =" + getcreatetime () + ", getclass () =" + getclass () + ", hashcode () =" +hashcode ()+ ", toString () =" +Super. toString () + "]"; }        }
View Code

The Orderscustom class inherits the Orders class, and the Orderscustom class includes all the fields of the Orders class, only the user's information field is defined.

1.1.3, Mapper.xml
<mapper namespace= "Com.lhx.mybatis.mapperproxy.OrderMapper" >    <!--Check all order information--    <select id= " Findorderslist "resulttype=" Com.lhx.mybatis.po.OrdersCustom ">        Select        orders. *,        user.username,        user.address        from        orders, user        = user.id    </ Select></mapper>
1.1.4, Mapper Interface:
     Public throws Exception;
1.1.5, test:
 PackageCom.lhx.mybatis.mapperproxy;ImportJava.io.InputStream;Importjava.util.List;Importorg.apache.ibatis.io.Resources;Importorg.apache.ibatis.session.SqlSession;Importorg.apache.ibatis.session.SqlSessionFactory;ImportOrg.apache.ibatis.session.SqlSessionFactoryBuilder;ImportCom.lhx.mybatis.po.OrdersCustom;Importjunit.framework.TestCase; Public classOrdermappertestextendsTestCase {Privatesqlsessionfactory sqlsessionfactory; protected voidSetUp ()throwsException {//mybatis configuration fileString resource = "Sqlmapconfig-mapperproxy.xml"; InputStream InputStream=Resources.getresourceasstream (Resource); //Create sessionfactory using SqlsessionfactorybuilderSqlsessionfactory =NewSqlsessionfactorybuilder (). Build (InputStream); }     Public voidTestfindorderslist ()throwsException {//Get Sessionsqlsession session =sqlsessionfactory.opensession (); //Limited Mapper Interface instanceOrdermapper ordermapper = Session.getmapper (ordermapper.class); //Inquire about order informationlist<orderscustom> list =ordermapper.findorderslist ();        SYSTEM.OUT.PRINTLN (list);  for(intI=0,len = List.size (); i<len;i++) {System.out.println (List.get (i)); }        //Close SessionSession.close (); }}
View Code1.1.6, Summary: Defines a specialized PO class as the output type, which defines all the fields of the SQL query result set. This method is relatively simple and widely used in enterprises. 1.2, method Two "Resultmap": Use Resultmap, define specialized resultmap to map one-to-one query results. 1.2.1 SQL statement: Ibid. 1.2.2, define PO class in the Orders class to add the user property, the users property to store the information associated with the query, because the Order Association query user is a one-to-a-relationship, so here use a single User object to store the information associated with the query. 1.2.3, Mapper.xml
    <id= "Findorderslistresultmap"  resultmap= "Userordermap"  >        SELECT        orders.*,        user.username,        user.address        from        orders, user        WHERE orders.user_id =        user.id    </Select>

Here Resultmap specifies Userordermap.

1.2.4, defining RESULTMAP needs to correlate query mappings with user information, using association to map user information to the user properties of the order object.
    <!--Order Information Resultmap -    <Resultmaptype= "Com.lhx.mybatis.po.Order"ID= "Userordermap">        <!--The ID here is mybatis to use when mapping the user field to a user object when making a one-to-one query, must write -        <ID Property= "id"column= "id" />        <result Property= "user_id"column= "user_id" />        <result Property= "Number"column= "Number" />        <Association Property= "User"Javatype= "Com.lhx.mybatis.po.User">            <!--The ID for this is the ID of the user, and if you write the id attribute assigned to the user -            <ID Property= "id"column= "user_id" />            <result Property= "username"column= "username" />            <result Property= "Address"column= "Address" />        </Association>    </Resultmap>

Association: Represents a single record of an association query

Property: The result of the associated query is stored in the user attribute of order Javatype: Indicates the result type of the associated query <id property= "id" column= "user_id"/&GT;: User_ of query results The ID column corresponds to the id attribute of the associated object, where <id/> Indicates that user_id is the unique identity of the associated query object. <result property= "username" column= "username"/&GT;: the username column of the query result corresponds to the Username property of the associated object. 1.2.5 Mapper Interface:
    throws Exception;
1.2.6 Test:
     Public voidTestfindorderslistresultmap ()throwsException {//Get Sessionsqlsession session =sqlsessionfactory.opensession (); //Limited Mapper Interface instanceOrdermapper ordermapper = Session.getmapper (ordermapper.class); //Inquire about order informationlist<order> list =Ordermapper.findorderslistresultmap ();        SYSTEM.OUT.PRINTLN (list);  for(inti = 0, Len = list.size (); i < Len; i++) {System.out.println (List.get (i)); }        //Close SessionSession.close (); }
1.2.7, Summary: Use association to complete the associated query and map the associated query information to the Pojo object. Implementation of a one-to-one query: Resulttype: Using the Resulttype implementation is relatively simple, if the Pojo does not include the queried column names, you need to increase the column name corresponding to the property, you can complete the mapping. It is recommended to use Resulttype if there is no special requirement for query results. Resultmap: You need to define the RESULTMAP separately, the implementation is a bit cumbersome, if the query results have special requirements, use RESULTMAP can complete the association query mapping Pojo Properties. Resultmap can implement lazy loading, resulttype cannot implement lazy loading.

java-mybaits-00502-Case-mapping analysis-pair of one or one-to-many, many-to-many

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.