Java Web simple mall project (III)

Source: Internet
Author: User

Java Web simple mall project (III)
I. general BaseDao. java

Since everyone needs to use it, the generic type is used. The problems that need to be paid attention to are similar.User. getClass (). getName ()Such code needs to be modified. The modification method is to use parameters.Class tcPass it over, and then useTc. getName ()You can.

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
  
   
{/*** Retrieve a T type based on the id * @ param id the id of the T type * @ return */public T load (Class
   
    
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 the T type to be added * @ return true success */public boolean add (T t) {int isAdd = 0; sqlSession session = SessionUtil. getSession (); try {isAdd = session. insert (t. getClass (). getName () + ". add ", t); session. commit (); // submit} catch (Exception e) {session. rollback (); // rollback if the submission fails} finally {SessionUtil. closeSession (session);} return isAdd> 0 ;} /*** delete T type based on id * @ param id to delete T * @ return true success */public boolean delete (Class
    
     
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 (); // System is returned for failed requests. out. println ("failed to delete user"); e. printStackTrace ();} finally {SessionUtil. closeSession (session);} return isDelete> 0 ;} /* ** update T type * @ param t user to be updated * @ return true success */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 (); // System is returned for failed requests. out. println ("failed to update user"); e. printStackTrace ();} finally {SessionUtil. closeSession (session);} return isUpdate> 0;}/*** query by Page Based on the specified condition * @ param maps specify the condition set * @ return */public Pager
     
      
Find (Class
      
        T, Map
       
         Maps) {int pageStart = SystemContext. getPageStart (); // int pageSize = SystemContext. getPageSize (); // Pager
        
          Pagers = new Pager <> (); maps. put ("pageStart", pageStart); maps. put ("pageSize", pageSize); SqlSession session = SessionUtil. getSession (); List
         
           Datas = null; try {datas = session. selectList (t. getName () + ". find ", maps); // retrieve the record pagers. setDatas (datas); pagers. setPageSize (pageSize); pagers. setPageStart (pageStart); int totalRecord = session. selectOne (t. getName () + ". findcount ", maps); // retrieve the total number of records pagers. setTotalRecord (totalRecord); pagers. setPageIndex (pageStart/pageSize + 1);} finally {SessionUtil. closeSession (session);} return pagers;}/*** retrieve some data based on specified conditions * @ param maps specified condition set * @ return */public Pager
          
            List (Class
           
             T, Map
            
              Maps) {Pager
             
               Pagers = new Pager <> (); SqlSession session = SessionUtil. getSession (); List
              
                Datas = null; try {datas = session. selectList (t. getName () + ". list ", maps); // retrieve the record pagers. setDatas (datas); pagers. setTotalRecord (datas. size ();} finally {SessionUtil. closeSession (session) ;}return pagers ;}}
              
             
            
           
          
         
        
       
      
     
    
   
  

The same UserDao. java needs to be modified accordingly.

Public class UserDao extends BaseDao
  
   
{/*** Retrieve a User by id * @ param id the User id * @ return */public User load (int id) {return super. load (User. class, id);}/* Other functions are different, all of which are similar */}
  
Ii. resing of resultMap

To put it simply, when the field information in the database is inconsistent with the object property, you must passResultMapTo map.
For example:AddressThere isUserObject class, as shown below:

Public class Address {private int id; private String name; private String phone; private String postcode; // directly give the user object to replace user_id private User user; '''''''''}

Then we want to obtainAddressAnd obtain the correspondingUserHowever, this is two objects, both of which have the id attribute. Therefore, for mybatisSetThe method is confusing when setting properties.ResultMapThe purpose is to eliminate such confusion.

Write load SQL

<code class="hljs xml"><!--{cke_protected}{C}%3C!%2D%2D%E5%8A%A0%E8%BD%BD%E4%B8%80%E4%B8%AA%E5%9C%B0%E5%9D%80%2D%2D%3E-->    <!--{cke_protected}{C}%3C!%2D%2D%E8%BF%99%E9%87%8C%E9%9C%80%E8%A6%81%E8%A1%A8%E8%BF%9E%E6%8E%A5%2C%E5%8F%96%E5%87%BAUser%2C%E5%8F%88%E8%BF%9E%E6%8E%A5%E4%BF%9D%E8%AF%81%E5%8F%96%E5%87%BA%E7%9A%84%E5%9C%B0%E5%9D%80%E4%B8%8D%E4%B8%BA%E7%A9%BA%2C%E5%B9%B6%E4%B8%94%E4%B8%BA%E9%87%8D%E5%A4%8D%E5%B1%9E%E6%80%A7id%E5%8F%96%E5%88%AB%E5%90%8D%2D%2D%3E-->    <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></code>

Here we use the resultMap for ing. The name of this resultMap is addressMap.

AddressMap

<code class="hljs xml"><resultmap automapping="true" id="addressMap" type="Address">        <!--{cke_protected}{C}%3C!%2D%2D%E6%8A%8A%E7%BB%93%E6%9E%9C%E4%B8%AD%E7%9A%84a_id%E6%98%A0%E5%B0%84%E4%B8%BAid%2C%E5%85%B6%E4%BB%96%E7%9A%84autoMapping%20%3D%20true%E4%BC%9A%E8%87%AA%E5%8A%A8%E5%8C%B9%E9%85%8D%2D%2D%3E-->        <id column="a_id" property="id">        <!--{cke_protected}{C}%3C!%2D%2D%E5%8F%96%E5%87%BA%E5%85%B3%E8%81%94%E5%B1%9E%E6%80%A7%2D%2D%3E-->        <association javatype="User" property="user">        <!--{cke_protected}{C}%3C!%2D%2D%E6%8A%8Auser_id%E6%98%A0%E5%B0%84%E4%B8%BAuser%E7%9A%84id%2D%2D%3E-->            <id column="user_id" property="id">            <result column="username" property="username">            <result column="nickname" property="nickname">            <result column="type" property="type">        </result></result></result></id></association>    </id></resultmap></code>
Type indicates its type, and autoMapping true, which is not included in the association attribute, indicates that after the conflict is eliminated, the remaining attributes will automatically match the values of id and result mapped to a single column to a simple data type, the difference is that the result indicated by id is the identity attribute used when the object instance is compared. Generally, the primary key association represents the association attribute. Here the User is set, For Association ing, the property to be displayed must be manually specified. Otherwise, the property cannot be mapped.

After the above configuration is complete, mybatis will automatically call its corresponding set method when searching out, and set the attribute to the object class.

Test

package com.dao;import com.model.Address;public class AddressDao extends BaseDao{Public static void main (String [] args) {AddressDao addressDao = new AddressDao (); Address address Address = addressDao. load (1); System. out. println (address. toString ();}/*** load an address * @ param id of the address to be loaded * @ return returns the address to be loaded, loading fails if null */public Address load (int id) {return super. load (Address. class, id );}}

It can be seen that as long as all the associated attributes of the ing are taken out, all those not mapped are null.

Use this idea to complete other functions <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> Vc3ryb25np1_vcd4ncjxwpnhtblt6wus6pc9wpg0kphbyzsbjbgfzcz0 = "brush: java;"> <code class = "hljs xml"> <! -- {Cke_protected} {C} % 3C! % 2D % 2D % 3 Fxml % 20 version % 3D % 221.0% 20 encoding % 3D % 22UTF-8% 22% 22% 3F % 2D % 2D % 3E --> <mapper namespace = "com. model. address "> <! -- {Cke_protected} {C} % 3C! % 2D % 2D % E5 % BD % 93% E6 % 95% B0 % E6 % 8D % AE % E5 % BA % 93% E4 % B8 % AD % E7 % 9A % 84% E5 % AD % 97% E6 % AE % B5 % E4 % BF % A1 % E6 % 81% AF % E5 % 92% 8C % E5 % AF % B9 % E8 % B1 % A1 % E7 % 9A % 84% E5 % B1 % 9E % E6 % 80% A7 % E4 % B8 % 8D % E4 % B8 % 80% E8 % 87% B4 % E6 % 97% B6 % E9 % 9C % 80% E8 % a6 % 81% E9 % 80% 9A % E8 % BF % 87 resultMap % E6 % 9D % A5 % E6 % 98% A0 % E5 % B0 % 84% 2D % 2D % 3E --> <resultmap automapping = "true" id = "addressMap" type = "Address"> <! -- {Cke_protected} {C} % 3C! % 2D % 2D % E6 % 8A % 8A % E7 % BB % 93% E6 % 9E % 9C % E4 % B8 % AD % E7 % 9A % 84a_id % E6 % 98% A0 % E5 % B0 % 84% E4 % B8 % BAid % 2C % E5 % 85% B6 % E4 % BB % 96% E7 % 9A % 84 autoMapping % 20% 3D % 20 true % E4 % BC % 9A % E8 % 87% AA % E5 % 8A % A8 % E5 % 8C % B9 % E9 % 85% 8D % 2D % 2D % 3E --> <id column = "a_id" property =" id "> <! -- {Cke_protected} {C} % 3C! % 2D % 2D % E5 % 8F % 96% E5 % 87% BA % E5 % 85% B3 % E8 % 81% E5 % B1 % 9E % E6 % 94% A7 % 2D % 2D % 3E --> <association javatype = "User" property = "user"> <! -- {Cke_protected} {C} % 3C! % 2D % 2D % E6 % 8A % 8Auser_id % E6 % 98% A0 % E5 % B0 % 84% E4 % B8 % BAuser % E7 % 9A % 84id % 2D % 2D % 3E --> <id column = "user_id" property = "id"> <result column = "username" property = "username"> <result column = "nickname" property = "nickname"> <result column = "type" property = "type"> </result> </id> </association> </id> </resultmap> <! -- {Cke_protected} {C} % 3C! % 2D % 2D % E5 % 8A % A0 % E8 % BD % E4 % B8 % 80% E4 % B8 % AA % E5 % 9C % B0 % E5 % 9D % 80% 2D % 2D % 3E --> <! -- {Cke_protected} {C} % 3C! % 2D % 2D % E8 % BF % 99% E9 % 87% 8C % E9 % 9C % 80% E8 % A6 % 81% E8 % A1 % A8 % E8 % BF % 9E % E6 % 8E % A5 % 2C % E5 % 8F % 96% E5 % 87% BAUser % 2C % E5 % 8F % 88% E8 % BF % 9E % E6 % 8E % A5 % E4 % BF % 9D % e8 % AF % 81% E5 % 8F % 96% E5 % 87% BA % E7 % 9A % 84% E5 % 9C % B0 % E5 % 9D % 80% E4 % B8 % 8D % E4 % B8 % BA % E7 % A9 % BA % 2C % E5 % B9 % B6 % E4 % B8 % 94% E4 % B8 % BA % E9 % 87% 8D % E5 % A4 % 8D % E5 % B1 % 9E % E6 % 80% A7id % E5 % 8F % 96% E5 % 88% AB % E5 % 90% 8D % 2D % 3E --> <select id = "load" parametertype = "int" resultmap = "addressMap"> select *, t1.id 'A _ id' from address t1 right join user t2 ON (t1.user _ id = t2.id) WHERE t1.id =#{ id}; </select> <! -- {Cke_protected} {C} % 3C! % 2D % 2D % E5 % A2 % 9E % E5 % 8A % A0 % E4 % B8 % 80% E4 % B8 % AA % E5 % 9C % B0 % E5 % 9D % 80% 2D % 2D % 3E --> <insert id = "add" parametertype = "Address"> insert into address values (null, # {name}, # {phone}, # {postcode}, $ {user_id}) </insert> <! -- {Cke_protected} {C} % 3C! % 2D % 2D % E5 % 88% A0 % E9 % 99% A4 % E4 % B8 % 80% E4 % B8 % AA % E5 % 9C % B0 % E5 % 9D % 80% 2D % 2D % 3E --> <delete id = "delete" parametertype = "int"> delete from address WHERE id =#{ id} </delete> <! -- {Cke_protected} {C} % 3C! % 2D % 2D % E4 % BF % AE % E6 % 94% B9 % E4 % B8 % 80% E4 % B8 % AA % E5 % 9C % B0 % E5 % 9D % 80% 2D % 2D % 3E --> <update id = "update" parametertype = "Address"> UPDATE address SET name =#{ name }, phone =#{ phone}, postcode =#{ postcode} where id =#{ id} </update> <! -- {Cke_protected} {C} % 3C! % 2D % 2D % E6 % 89% BE % E5 % 87% BA % E6 % 8C % 87% E5 % AE % 9A % E7 % 94% A8 % E6 % 88% B7 % E6 % 89% e6 % 9C % 89% E7 % 9A % 84% E5 % 9C % B0 % E5 % 9D % 80% 2D % 2D % 3E --> <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> </code>

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 { public static void main(String[] args) { AddressDao addressDao = new AddressDao(); PagerPagers = addressDao. list (1); System. out. println (pagers. getDatas (). size ();}/*** load an address * @ param id of the address to be loaded * @ return returns the address to be loaded, loading fails if null */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 success */public boolean add (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: id corresponding to the address to be deleted * @ return true: deleted 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 successful */public boolean update (address Address) {return super. update (address);}/*** retrieve all user addresses based on the user ID * @ param user_id * @ return */public Pager list(int user_id){ Map  maps = new HashMap<>(); maps.put("user_id",user_id); return super.list(Address.class,maps); }} 

If the ADO layer is written in this way, no problem will occur. The entity DAO code behind it will not be attached. The next article on factory model learning

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.