MyBatis Advanced Mapping Learning Tutorial _java

Source: Internet
Author: User
Tags inheritance null null unique id

A friend who is not very clear about the basics of MyBatis can refer to this article: MyBatis Introductory Learning Tutorial (i)-mybatis QuickStart.

Know MyBatis

MyBatis is an open source project for Apache Ibatis, the project was migrated from Apache Software Foundation to Google code in 2010 and renamed MyBatis. November 2013 migrated to GitHub.
The word ibatis is derived from the combination of "Internet" and "Abatis", a Java-based persistence layer framework. The persistence layer framework provided by Ibatis includes SQL maps and Data Access Objects (DAO)

MyBatis Atlas

Brief introduction

Previously said a simple database query and management query, in the development requirements of a few pairs of more than one or one and many-to-many requirements development, such as in the development of shopping carts, orders and users are one-to-one, users and orders are One-to-many, users and goods are many pairs. These are also common in hibernate development, hibernate are implemented through data mapping, and in MyBatis are also implemented through configuration file data maps.

One-to-one query

If we want to query the order information, the associated query creates the user information of the order, then this is a typical one-to-one query. There are two ways to implement one-to-one queries: using Resulttype and Resultmap. Resulttype requires an additional definition of pojo and then corresponds to the field of the query and the newly defined Pojo one by one. Resultmap requires a configuration file to implement a one-to-one association of two Pojo. Here are the two ways to implement them separately.

  Resulttype:

1, create the Pojo, add the new attributes that need to be mapped to the new Pojo.

 public class OrderCustom extends orders{
   //Add user Information
   private String username;
   Private String sex;
   Private String address;
   Public String GetUserName () {return
     username;
   }
   public void Setusername (String username) {
     this.username = username;
   }
   Public String Getsex () {return
     sex;
   }
   public void Setsex (String sex) {
     this.sex = sex;
   }
   Public String getaddress () {return address
     ;
   }
   public void setaddress (String address) {
     this.address = address;
   }
 }

  2, mapping File:

 <select id= "Findorderuser" resulttype= "Com.luchao.mybatis.first.po.OrderCustom" >
     Select
     orders.* ,
     User.username,
     user.sex,
     user.address from
     orders,user
     where
     orders.user_id = User.ID
 </select>

  3, the implementation of the Mapper interface:

Query Order and user information public
 list<ordercustom> Findorderuser () throws Exception;

  4. Test code:

 public void Findordersuser () throws Exception {
     //Get Sqlsession object
     sqlsession = Sqlsessionfactory.opensession ();
     Create Ordermapper object, MyBatis automatically generate mapper proxy
     ordermapper ordermapper = Sqlsession.getmapper (ordermapper.class);
     Calls the Ordermapper method, inquires the order and the user information
     list<ordercustom> ordercustoms = Ordermapper.findorderuser ();
     System.out.println (Ordercustoms.size ());
 }

  Resultmap implementation:

Resultmap maps The order information in the query results to the Orders object, adds the user property to the orders class, and maps the user information from the associated query into the user attribute in the Orders object.

  1, create Pojo, add the user attribute in the Order class.

public class Orders {private Integer ID;
   Private Integer userId;
   private String number;
   Private Date Createtime;
   private String Note;
   User information private users user;
   Order Entry private list<orderdetail> OrderDetails;
   Public Integer GetId () {return id;
   The public void SetId (Integer id) {this.id = ID;
   Public Integer GetUserID () {return userId;
   The public void Setuserid (Integer userId) {this.userid = UserId;
   Public String GetNumber () {return number;
   public void Setnumber (String number) {this.number = number = null Null:number.trim ();
   Public Date Getcreatetime () {return createtime;
   The public void Setcreatetime (Date createtime) {this.createtime = Createtime;
   Public String Getnote () {return note;
   public void Setnote (String note) {this.note = Note = null Null:note.trim ();
   Public user GetUser () {return user; } publicvoid SetUser (user user) {this.user = user;
   Public list<orderdetail> GetOrderDetails () {return orderdetails;
   public void Setorderdetails (list<orderdetail> orderdetails) {this.orderdetails = OrderDetails; }  
 }

2, mapping file:

 <!--order Query the Resultmap of the associated users, map the entire query results to orders--> <resultmap type= "com.luchao.mybatis.first.po.Orders" id= " Ordersuserresultmap "> <id column=" id "property=" id "/> <result" column= user_id "property=" UserId "/&"
     Gt <result column= "number" property= "number"/> <result column= "createtime" property= "Createtime"/> &L T;result column= property= "Note"/> <!--the associated user information for the configuration map--> <!--Association: Information for mapping an associated query individual object Pro Perty: To map the user information of the associated query to which attribute in orders--> <association property= "user" javatype= "Com.luchao.mybatis.first.po.User" > <!--ID: The unique ID of the associated query user column: Specifies which property is mapped to user--> <id column= "user_id" Prope  rty= "id"/> <result column= "username" property= "username"/> "<result column=" sex "property=" sex " /> <result column= "Address" property= "Address"/> </association> </resultMap> <se Lect id= "FindorderusermAP "resultmap=" Ordersuserresultmap "> select orders.*, User.username, User.sex, user.address From orders,user where orders.user_id = User.ID </select>

Association: Used to map information about a single object for an associated query, property: To map the user information of an associated query to which attribute in orders.

  3, Mapper interface

 Query orders and user information via Resultmap public
 list<orders> Findorderusermap () throws Exception;

  4. Test code:

public void Findordersusermap () throws Exception {
     //Get Sqlsession object
     sqlsession = Sqlsessionfactory.opensession ();
     Create Ordermapper object, MyBatis automatically generate mapper proxy
     ordermapper ordermapper = Sqlsession.getmapper (ordermapper.class);
     Call the Ordermapper method, query order and user information
     list<orders> orders = Ordermapper.findorderusermap ();
     System.out.println (Orders.size ());
 }

  Resulttype and Resultmap realize a one-to-one query summary:

Resulttype: Using the Resulttype implementation is simpler, if the Pojo does not include the query out of the column name, you need to increase the column name corresponding to the property, you can complete the mapping. Resulttype is recommended if there are no special requirements for query results.

Resultmap: Need to define the RESULTMAP, the implementation is a bit cumbersome, if there are special requirements for query results, using RESULTMAP can be completed to map the associated query Pojo properties. Resultmap can implement deferred loading, Resulttype cannot implement deferred loading.

One-to-many Query

If you need to query the order and order details of the information, then this is a one-to-many query requirements.

1, Pojo and the order of the above Resultmap the same pojo, the orders are set to the list as a property.

2, mapping File:

 <!--orders and order details and user information map use inheritance do not--> <resultmap type= "com.luchao.mybatis.first.po.Orders" id= "Orderso" To configure order and user information Rderdetailresultmap "extends=" Ordersuserresultmap "> <collection property=" orderdetails "ofType=" com . luchao.mybatis.first.po.Orderdetail "> <result column=" orderdetail_id "property=" id "/> <result Column= "items_id" property= "Itemsid"/> <result column= "Items_num" property= "Itemsnum"/> <resul T column= "orders_id" property= "Ordersid"/> </collection> </resultMap> <select id= "Findorderand
     Orderdetailmap "resultmap=" Ordersorderdetailresultmap "> select orders.*, User.username, User.sex, User.address, Orderdetail.id orderdetail_id, orderdetail.items_id, Orderdetail.items_num, Orderdet ail.orders_id from orders,user,orderdetail where orders.user_id = user.id and orderdetail.orders_id = Orders.id </select&Gt 

Order and order details of the Resultmap, using extends inheritance, do not have to configure the order information and user Information mapping.

Collection: Maps an associated query to multiple records to a collection object, property: Maps an associated query to multiple records to which attribute of the orders.

OfType: Specifies the type that maps to the Pojo in the List collection property, and note that there is a difference between ofType and one-to-one.

3, Mapper Interface:

Query orders, Order details and user information via Resultmap
Public list<orders> Findorderandorderdetailmap () throws Exception;

4. Test code:

public void Findorderandorderdetailmap () throws Exception {
     //Get Sqlsession object
     sqlsession = Sqlsessionfactory.opensession ();
     Create Ordermapper object, MyBatis automatically generate mapper proxy
     ordermapper ordermapper = Sqlsession.getmapper (ordermapper.class);
     Call the Ordermapper method, query order and user information
     list<orders> orders = Ordermapper.findorderandorderdetailmap ();
     System.out.println (Orders.get (). GetOrderDetails (). Size ());
     System.out.println (Orders.size ());
   }

 A one-to-many Summary:

MyBatis uses Resultmap's collection to map multiple records of an associated query to a list collection property.

Using Resulttype implementation:

Map the order details to orders in the OrderDetails, you need to deal with, use double loop traversal, remove duplicate records, put order details in the OrderDetails. This will be more troublesome.

Many to many

If we query users and users to buy merchandise information, this is Many-to-many, you can use mybatis multiple mapping.

Maps user information to users. Add order list properties to the user class list<orders> orderslist, map user-created orders to orderslist, add order Detail list attributes to orders list<orderdetail> Orderdetials, map the order details to Orderdetials, add the items attribute to the OrderDetail, and map the items corresponding to the order details to items.

  1, POJO

public class OrderDetail {private Integer ID;
   Private Integer Ordersid;
   Private Integer Itemsid;
   Private Integer Itemsnum;
   Commodity information private items items;
   Public Integer GetId () {return id;
   The public void SetId (Integer id) {this.id = ID;
   Public Integer Getordersid () {return ordersid;
   The public void Setordersid (Integer ordersid) {this.ordersid = Ordersid;
   Public Integer Getitemsid () {return itemsid;
   The public void Setitemsid (Integer itemsid) {this.itemsid = Itemsid;
   Public Integer Getitemsnum () {return itemsnum;
   The public void Setitemsnum (Integer itemsnum) {this.itemsnum = Itemsnum;
   Public Items GetItems () {return items;
   public void Setitems (items items) {this.items = items; @Override public String toString () {return "OrderDetail [id= + ID +", ordersid= "+ Ordersid +", Itemsid= "+ Itemsid +", itemsnum= "+ Itemsnum +"];
   } 
 } 

2, mapping file:

<!--inquire the user and purchase the merchandise--> <resultmap type= "Com.luchao.mybatis.first.po.User" id= "Ordersitemsresultmap" > ;! --User information--> <id column= "user_id" property= "id"/> <result column= "username" property= "username"/&gt
     ; <result column= "Sex" property= "sex"/> <result column= "Address" property= "Address"/> <!--order information A user corresponds to multiple orders, using the collection mapping--> <collection property= "orderslist" oftype= "Com.luchao.mybatis.first.po.Orders" > <id column= "id" property= "id"/> <result column= "user_id" property= "UserId"/> <r Esult column= "number" property= "number"/> <result column= "createtime" property= "Createtime"/> ; result column= "note" property= "/> <!--Order Details an order includes multiple details--> <collection property=" Orderde
         Tails "oftype=" Com.luchao.mybatis.first.po.Orderdetail "> <id column=" id "property=" id "/> <result ColumN= "items_id" property= "Itemsid"/> <result column= "Items_num" property= "Itemsnum"/> <result Column= "orders_id" property= "Ordersid"/> <!--commodity information an order detail corresponding to a product--> <association property= "Items" javatype= "Com.luchao.mybatis.first.po.Items" > <id column= "items_id" property= "id"/&gt
           ;
           <result column= "Items_name" property= "name"/> <result "column=" Items_detail "property=" detail
     <result column= "Items_price" property= "price"/> </association> </collection>
     </collection> </resultMap> <select id= "Findorderanditemmap" resultmap= "Ordersitemsresultmap" > Select Orders.*, User.username, User.sex, user.address, orderdetail.id orderdetail_id, O rderdetail.items_id, Orderdetail.items_num, orderdetail.orders_id, Items.id items_id, items.name items
    _name, Items.detail Items_detail, Items.price items_price from Orders,user,orderdetail,items where orders.user_id = User.ID and orderdetail.orders_id = orders.id and orderdetail.items_id = Items.id </select>

It can be seen that many pairs is basically a one-to-many and one-to-one combination, all complex problems are basically a combination of simple problems, as long as the careful analysis, the rationale of the principle.

 3, Mapper Interface:

 Search orders, Order details and user information via Resultmap public
 list<user> Findorderanditemmap () throws Exception;

 4. Test code:

public void Findorderanditemmap () throws Exception {
     //Get Sqlsession object
     sqlsession = Sqlsessionfactory.opensession ();
     Create Ordermapper object, MyBatis automatically generate mapper proxy
     ordermapper ordermapper = Sqlsession.getmapper (ordermapper.class);
     Call the Ordermapper method, query order and user information
     list<user> users = Ordermapper.findorderanditemmap ();
     System.out.println (Users.get (). Getorderslist (). Get ().
         getorderdetails (). Get (). GetId ());
     System.out.println (Orders.size ());
 }

  Multiple to multiple query summary:

The above requirement uses Resulttype to map the queried records to an extended Pojo, which simply implements the functionality of the detail list, but this does not implement deferred loading. You can implement deferred loading by using Resultmap to map the itemized list of items purchased by a user to an object. The use of Resultmap is for those features that have special requirements for mapping query results, such as special requirements mapped into lists that include multiple lists.

Resultmap Summary

  1, Resulttype:

Role:

The query results are mapped to Pojo in accordance with the SQL column name Pojo property name consistency.

Occasion:

Some common details of the display of records, such as user purchase details, the relevant query information all displayed in the page, at this time can directly use Resulttype to map each record to Pojo, in the front-end Page traversal list (list is Pojo) can be.

2, Resultmap:

Complete one-to-one and One-to-many advanced Mappings with Association and collection (special mapping requirements for results).

Association:

Role:

Maps the associated query information to a Pojo object.

Occasion:

To facilitate Query association information, you can use association to map the associated order information to the Pojo attribute of the user object, such as: query order and associated user information.

Using Resulttype, you cannot map query results to the Pojo properties of Pojo objects, choosing whether to use Resulttype or Resultmap depending on the needs of the query traversal for the result set.

Collection

Role:

Maps the associated query information to a list collection.

Occasion:

In order to facilitate the query traversal correlation information can use collection to map the correlation information to the list collection, for example: Query user permission scope module and the menu under the module, can use collection to map the module to the module list, Map the menu list to the Menu list property of the module object, which is designed to facilitate traversal queries on the query result set.

If you use Resulttype, you cannot map query results to the list collection.

The above content is small series to introduce the MyBatis Advanced Mapping Learning course, hope to help everyone, if you want to know more content, please pay attention to cloud Habitat community website!

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.