For those who are not very clear about the basics of mybatis, please refer to this article: MyBatis introduction learning tutorial (I) - MyBatis quick introduction.
Meet MyBatis
MyBatis is an open source project of apache. In 2010, this project was moved from apache software foundation to Google code and was renamed MyBatis. Migrated to Github in November 2013.
The term iBATIS comes from the combination of "internet" and "abatis", and is a Java-based persistence layer framework. iBATIS provides persistence layer frameworks including SQL Maps and Data Access Objects (DAO)
mybatis picture album
Introduction
I mentioned the simple database query and management query before. There are some one-to-one, one-to-many and many-to-many demand development in the development requirements. For example, when developing shopping carts, the orders and users are one-to-one, the users and orders are one-to-many, and the users and products are many-to-many. These are also common in Hibernate development. They are implemented through data mapping in Hibernate, and in MyBatis, they are implemented through data mapping in configuration files.
One-to-one query
If we want to query order information and associate query user information for creating orders, then this is a typical one-to-one query. There are two ways to implement one-to-one query: use resultType and resultMap. resultType requires additional POJO definition, and then the query fields correspond to the newly defined POJO one by one. resultMap needs to implement one-to-one correlation between two POJOs through configuration files. Let’s implement these two methods separately below.
resultType:
1. Create a POJO and 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 files:
<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. Implementation of Mapper interface:
//Query order and user information public List<OrderCustom> findOrderUser() throws Exception;
4. Test code:
public void findOrdersUser() throws Exception { // Get the sqlSession object SqlSession sqlSession = sqlSessionFactory.openSession(); // Create the OrderMapper object, MyBatis automatically generates the mapper proxy OrderMapper orderMapper = sqlSession.getMapper(OrderMapper.class); // Call the orderMapper method to query order and user information List<OrderCustom> orderCustoms = orderMapper.findOrderUser(); System.out.println(orderCustoms.size()); }resultMap implementation:
resultMap maps the order information in the query result to the Orders object, adds the User attribute in the orders class, and maps the associated query user information to the user attribute in the orders object.
1. Create a POJO and add the User attribute to the Order class.
public class Orders { private Integer id; private Integer userId; private String number; private Date createtime; private String note; //User information private User user; //Order entry private List<Orderdetail> orderdetails; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getUserId() { return userId; } 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; } 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; } public void setUser(User user) { this.user = user; } public List<Orderdetail> getOrderdetails() { return orderdetails; } public void setOrderdetails(List<Orderdetail> orderdetails) { this.orderdetails = orderdetails; } }2. Mapping files:
<!-- Order query the resultMap of the associated user, map the entire query result to orders--> <resultMap type="com.luchao.mybatis.first.po.Orders" id="ordersUserResultMap"> <id column="id" property="id" /> <result column="user_id" property="userId" /> <result column="number" property="number" /> <result column="createtime" property="createtime" /> <result column="note" property="note" /> <!-- Configure the associated user information of the mapping--> <!-- association: Used to map information for an associated query single object property: Which property in Orders to map the user information of the associated query to --> <association property="user" javaType="com.luchao.mybatis.first.po.User"> <!-- id: Unique ID of the associated query user column: Specify the column that uniquely identifies user information javaType: Which property of the user map to --> <id column="user_id" property="id" /> <result column="username" property="username" /> <result column="sex" property="sex" /> <result column="address" property="address" /> </association> </resultMap> <select 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 of an associated query single object, property: Which property in Orders to map the user information of the associated query to.
3. Mapper interface
//Query order and user information through resultMap public List<Orders> findOrderUserMap() throws Exception;
4. Test code:
public void findOrdersUserMap() throws Exception { // Get the sqlSession object SqlSession sqlSession = sqlSessionFactory.openSession(); // Create the OrderMapper object, MyBatis automatically generates mapper proxy OrderMapper orderMapper = sqlSession.getMapper(OrderMapper.class); // Call the orderMapper method to query order and user information List<Orders> orders = orderMapper.findOrderUserMap(); System.out.println(orders.size()); }resultType and resultMap implement one-to-one query summary:
resultType: It is relatively simple to implement using resultType. If the query column name is not included in the pojo, you need to add the corresponding attributes of the column name to complete the mapping. If there are no special requirements for query results, it is recommended to use resultType.
resultMap: The resultMap needs to be defined separately, which is a bit troublesome. If there are special requirements for query results, using resultMap can complete the attributes of the associated query mapping pojo. resultMap can implement lazy loading, resultType cannot implement lazy loading.
One-to-many query
If you need to query the order and order details, then this is the one-to-many query requirement.
1. POJO is the same as the POJO of the Order in the resultMap above. Set the order details to List as the attribute of the Order.
2. Mapping files:
<!-- Map for order and order details and user information Use inheritance does not need to configure order and user information --> <resultMap type="com.luchao.mybatis.first.po.Orders" id="ordersOrderdetailResultMap" 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" /> <result column="orders_id" property="ordersId" /> </collection> </resultMap> <select id="findOrderAndOrderdetailMap" resultMap="ordersOrderdetailResultMap"> select orders.*, user.username, user.sex, user.address, orderdetail.id orderdetail_id, orderdetail.items_id, orderdetail.items_num, orderdetail.orders_id from orders,user,orderdetail where orders.user_id = user.id and orderdetail.orders_id = orders.id </select>
The resultMap of orders and order details is inherited using extends, and there is no need to configure the mapping of order information and user information.
collection: map multiple records to the collection object for the association query, property: map multiple records to the Orders property.
ofType: Specifies the type that maps to the pojo in the list collection attribute. Note that there is still a difference between ofType and one-to-one.
3. Mapper interface:
//Inquiry of orders, order details and user information through resultMap
public List<Orders> findOrderAndOrderdetailMap() throws Exception;
4. Test code:
public void findOrderAndOrderdetailMap() throws Exception { // Get the sqlSession object SqlSession sqlSession = sqlSessionFactory.openSession(); // Create the OrderMapper object, MyBatis automatically generates mapper proxy OrderMapper orderMapper = sqlSession.getMapper(OrderMapper.class); // Call the orderMapper method to query order and user information List<Orders> orders = orderMapper.findOrderAndOrderdetailMap(); System.out.println(orders.get().getOrderdetails().size()); System.out.println(orders.size()); }One-to-many summary:
mybatis uses resultMap's collection to map multiple records of the associated query into a list collection property.
Implementation using resultType:
Mapping order details into orderdetails in orders, you need to handle it yourself, use a double loop to traverse, remove duplicate records, and place order details in orderdetails. This will be more troublesome.
Many-to-many
If we query users and users’ purchase product information, this is many-to-many, and you can use MyBatis’ many-to-many mapping.
Map user information into user. Add the order list attribute List<Orders> orderslist in the user class, map the order created by the user to the orderslist, add the order details list attribute List<OrderDetail> orderdetials in the Orders, map the order details to orderdetials, add the Items attribute in 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; //Product information private Items items; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getOrdersId() { return ordersId; } public void setOrdersId(Integer ordersId) { this.ordersId = ordersId; } public Integer getItemsId() { return itemsId; } public void setItemsId(Integer itemsId) { this.itemsId = itemsId; } public Integer getItemsNum() { return itemsNum; } 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 files:
<!-- Query the user and purchased products--> <resultMap type="com.luchao.mybatis.first.po.User" id="ordersItemsResultMap"> <!-- User information--> <id column="user_id" property="id" /> <result column="username" property="username" /> <result column="sex" property="sex" /> <result column="address" property="address" /> <!-- Order information A user corresponds to multiple orders, use collection mapping--> <collection property="ordersList" ofType="com.luchao.mybatis.first.po.Orders"> <id column="id" property="id" /> <result column="user_id" property="userId" /> <result column="number" property="number" /> <result column="createtime" property="createtime" /> <result column="note" property="note" /> <!-- Order Details One order includes multiple details--> <collection property="orderdetails" 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" /> <!-- Product information One order details correspond to one product --> <association property="items" javaType="com.luchao.mybatis.first.po.Items"> <id column="items_id" property="id" /> <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, orderdetail.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-to-many is basically a combination of one-to-many and one-to-one. All complex problems are basically combinations of simple problems. As long as you analyze them carefully, you can understand the principles.
3. Mapper interface:
//Query order, order details and user information through resultMap public List<User> findOrderAndItemMap() throws Exception;
4. Test code:
public void findOrderAndItemMap() throws Exception { // Get the sqlSession object SqlSession sqlSession = sqlSessionFactory.openSession(); // Create the OrderMapper object, MyBatis automatically generates mapper proxy OrderMapper orderMapper = sqlSession.getMapper(OrderMapper.class); // Call the orderMapper method to 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()); }Many-to-many query summary:
The above requirements use resultType to map the queryed records into an extended pojo, which is very simple to implement the function of a detailed list, but this cannot implement lazy loading. Use resultMap to map a detailed list of items purchased by users to an object, which allows lazy loading. Using resultMap is for those functions that have special requirements for query result mapping, such as mapping special requirements into lists including multiple lists.
resultMap summary
1. resultType:
effect:
Map the query results into pojo according to the sql column name pojo attribute name consistency.
Occasion:
Common display of detailed records, such as when users purchase product details and display all the associated query information on the page, you can directly use resultType to map each record into a pojo, and traverse the list (pojo in the list) on the front-end page.
2. resultMap:
Use association and collection to complete one-to-one and one-to-many advanced mapping (there are special mapping requirements for the results).
association:
effect:
Map the associated query information into a pojo object.
occasion:
In order to facilitate querying associated information, you can use association to map associated order information into pojo attributes of user objects, such as: querying orders and associated user information.
Using resultType cannot map the query results to the pojo attribute of the pojo object. Choose whether to use resultType or resultMap according to the needs of traversing the result set query.
Collection:
effect:
Map the associated query information into a list collection.
occasion:
In order to facilitate querying traversal association information, you can use collection to map the association information to the list collection. For example: querying the user permission scope module and the menu under the module, you can use collection to map the module list to map the menu list attributes of the module object. The purpose of this is to facilitate traversal querying the query result set.
If you use resultType, you cannot map the query results to the list collection.
The above content is the MyBatis advanced mapping learning tutorial introduced to you by the editor. I hope it will be helpful to you. If you want to know more, please pay attention to the Wulin.com website!