Next, the previous article "Javaweb Practical Mall Project Development (II)" mainly implements the general BaseDao.java and uses resultMap to map related objects.
1. General BaseDao.java
Since everyone needs to use it, generics are used. The problem to note is that codes like User.getClass().getName() need to be modified. The modification method is to pass it with the parameter Class tc, and then use tc.getName().
Complete code:
package com.dao;import com.model.Pager;import com.util.SessionUtil;import com.util.SystemContext;import org.apache.ibatis.session.SqlSession;import java.util.HashMap;import java.util.List;import java.util.Map;/** * Created by nl101 on 2016/2/23. */public class BaseDao<T> { /** * Take out a T type based on id* @param id To remove the id of T type * @return */ public T load(Class<T> tc,int id){ SqlSession session = SessionUtil.getSession(); T t = null; try { t = session.selectOne(tc.getName()+".load",id); } finally { SessionUtil.closeSession(session); } return t; } /** * Add a T type* @param t T type to be added* @return true successful*/ public boolean add(T t){ int isAdd = 0; SqlSession session = SessionUtil.getSession(); try { isAdd = session.insert(t.getClass().getName()+".add",t); session.commit();//Commit} catch (Exception e) { session.rollback();//Rolle back if submission fails} finally { SessionUtil.closeSession(session); } return isAdd>0; } /** *Delete T type based on id* @param id To delete the id of T * @return true successful*/ public boolean delete(Class<T> t,int id){ int isDelete = 0; SqlSession session = SessionUtil.getSession(); try { isDelete = session.delete(t.getName()+".delete",id); session.commit(); } catch (Exception e) { session.rollback();//Failed Return System.out.println("Delete failed"); e.printStackTrace(); } finally { SessionUtil.closeSession(session); } return isDelete>0; } /** *Update T type* @param t User to be updated* @return true successful*/ public boolean update(T t){ int isUpdate = 0; SqlSession session = SessionUtil.getSession(); try { isUpdate = session.delete(t.getClass().getName()+".update",t); session.commit(); } catch (Exception e) { session.rollback();//Failed Return System.out.println("Update failed"); e.printStackTrace(); } finally { SessionUtil.closeSession(session); } return isUpdate>0; } /** *Paging query based on specified conditions* @param maps Specify condition collection* @return */ public Pager<T> find(Class<T> t,Map<String,Object> maps){ int pageStart = SystemContext.getPageStart();//Page start int pageSize = SystemContext.getPageSize();//Page size Pager<T> pages = new Pager<>(); maps.put("pageStart",pageStart); maps.put("pageSize",pageSize); SqlSession session = SessionUtil.getSession(); List<T> datas = null; try { datas = session.selectList(t.getName()+".find",maps);//Get the record pagers.setDatas(datas); pagers.setPageSize(pageSize); pagers.setPageStart(pageStart); int totalRecord = session.selectOne(t.getName()+".findcount",maps);//Get the total number of records pagers.setTotalRecord(totalRecord); pagers.setPageIndex(pageStart/pageSize+1); } finally { SessionUtil.closeSession(session); } return pagers; } /** * fetch part of the data according to the specified conditions* @param maps Specify the set of conditions* @return */ public Pager<T> list(Class<T> t,Map<String,Object> maps){ Pager<T> pages = new Pager<>(); SqlSession session = SessionUtil.getSession(); List<T> datas = null; try { datas = session.selectList(t.getName()+".list",maps);//Get record pagers.setDatas(datas); pagers.setTotalRecord(datas.size()); } finally { SessionUtil.closeSession(session); } return pagers; }}The same UserDao.java also requires corresponding modifications
public class UserDao extends BaseDao<User>{ /** * Remove a user based on the id* @param id To remove the user's id * @return */ public User load(int id){ return super.load(User.class,id); }/* Other functions are not posted one by one, they are all written in similar ways*/}2. Mapping of resultMap
Simply put, when the field information in the database is inconsistent with the attributes of the object, it is necessary to map through resultMap.
For example: There is a User entity class in the Address property, as follows
public class Address { private int id; private String name; private String phone; private String postcode; //Shit the user object directly instead of user_id private User user; ``````````}Then we want to take out an Address and also take out its corresponding user. However, these are two objects, and both have id attributes, so mybatis will be confused when calling the set method to set properties. The purpose of using resultMap is to eliminate this chaos.
Write load sql
<!--Load an address--> <!--The table connection is required here, and the User is taken out. The connection is also required to ensure that the retrieved address is not empty, and alias the duplicate attribute id--> <select id="load" parameterType="int" resultMap="addressMap"> select *,t1.id AS 'a_id' from address t1 RIGHT JOIN user t2 ON (t1.user_id = t2.id) WHERE t1.id=#{id}; </select>Here we use resultMap to map, the name of this resultMap is addressMap.
addressMap
<resultMap id="addressMap" type="Address" autoMapping="true"> <!--Mapping the a_id in the result as id, and other autoMapping = true will automatically match --> <id column="a_id" property="id"/> <!--Fetch the associated properties--> <association property="user" javaType="User" > <!--Mapping user_id as user's id--> <id column="user_id" property="id"/> <result column="username" property="username"/> <result column="nickname"/> <result column="nickname"/> <result column="nickname"/> <result column="type" property="type"/> </association> </resultMap>
After the above configuration is completed, when searching, mybatis will automatically call its corresponding set method and set the attributes to the entity class.
test
package com.dao;import com.model.Address;public class AddressDao extends BaseDao<Address> { public static void main(String[] args) { AddressDao addressDao = new AddressDao(); Address address = addressDao.load(1); System.out.println(address.toString()); } /** * Load an address* @param id The id of the address to be loaded * @return Return the address to be loaded, and null fails to load*/ public Address load(int id){ return super.load(Address.class,id); }} As can be seen in the renderings, as long as the mapping attributes are taken out, all those that are not mapped are null.
Follow this idea to complete other functions
xml code:
<?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"> <mapper namespace="com.model.Address"> <!-- When the field information in the database is inconsistent with the attributes of the object, you need to map it through resultMap--> <resultMap id="addressMap" type="Address" autoMapping="true"> <!--Map a_id in the result as id, other autoMapping = true will automatically match --> <id column="a_id" property="id"/> <!--Fetch the associated properties --> <association property="user" javaType="User" > <!--Map user_id to user's id --> <id column="user_id" property="id"/> <result column="username" property="username"/> <result column="nickname" property="nickname"/> <result column="nickname"/> <result column="type" property="type"/> </association> </resultMap> <!--Load an address --> <!--The table connection is required here, and the User is taken out. The connection ensures that the retrieved address is not empty, and aliasing it for the duplicate attribute id --> <select id="load" parameterType="int" resultMap="addressMap"> select *,t1.id AS 'a_id' from address t1 RIGHT JOIN user t2 ON (t1.user_id = t2.id) WHERE t1.id=#{id}; </select> <!--Add an address --> <insert id="add" parameterType="Address"> insert into address values (null,#{name},#{phone},#{postcode},${user_id}) </insert> <!--Delete an address--> <delete id="delete" parameterType="int"> DELETE FROM address WHERE id=#{id} </delete> <!--Modify an address--> <update id="update" parameterType="Address"> UPDATE address SET name=#{name},phone=#{phone},postcode=#{postcode} where id=#{id} </update> <!--Find out all addresses of the specified user--> <select id="list" parameterType="Map" resultMap="addressMap"> SELECT *,t1.id AS 'a_id' FROM address t1 RIGHT JOIN user t2 ON (t1.user_id=t2.id) WHERE t1.user_id=#{user_id} </select></mapper>java code:
package com.dao;import com.model.Address;import com.model.Pager;import java.util.HashMap;import java.util.Map;/** * Created by nl101 on 2016/2/23. */public class AddressDao extends BaseDao<Address> { public static void main(String[] args) { AddressDao addressDao = new AddressDao(); Pager<Address> pagers = addressDao.list(1); System.out.println(pagers.getDatas().size()); } /** * Load an address* @param id The id of the address to be loaded * @return Return the address to be loaded, and null fails */ public Address load(int id){ return super.load(Address.class,id); } /** * Add an address* @param address The address to be added* @param user_id The user_id corresponding to the address to be added * @return true successful*/ public boolean address(Address address,int user_id){ UserDao userDao = new UserDao(); if (userDao.load(user_id)==null){ return false; } return super.add(address); } /** * Delete an address* @param id To delete the id corresponding to the address * @return true Delete successfully*/ public boolean delete(int id){ return super.delete(Address.class,id); } /** * Update an address* @param address The address to be updated* @return true Update successfully*/ public boolean update(Address address){ return super.update(address); } /** * Update an address* @param address The address to be updated* @return true Update successfully*/ public boolean update(Address address){ return super.update(address); } /** * Take out all addresses of the user based on the user id * @param user_id * @return */ public Pager<Address> list(int user_id){ Map<String,Object> maps = new HashMap<>(); maps.put("user_id",user_id); return super.list(Address.class,maps); }}If the ADO layer is written in this way, there will be no problem.
The above is all about this article. This is all about the development of the entire javaweb mall project. I hope it will be helpful to your learning.