Javaweb Real-Battle Mall project Development (ii) _java

Source: Internet
Author: User
Tags rollback

The last article "Javaweb actual Combat Mall project development (i)" has been the entity class, paging tool to create a good, this article using MyBatis to create a DAO layer.

The other MyBatis API documentation can be referenced

I. Use of MyBatis

1. Introduction of the Rack package

This introduces MyBatis and MySQL to Lib.


2. Write Config.xml configuration database environment

Put the code on first, then explain it one by one

<?xml version= "1.0" encoding= "Utf-8"?> <! DOCTYPE configuration Public "-//mybatis.org//dtd Config 3.0//en" "Http://mybatis.org/dtd/mybatis-3-config.dtd"
; <configuration> <properties resource= "config.properties"/> <typeAliases> <package name= "COM.M
      Odel "/> </typeAliases> <environments default=" Development "> <environment id=" Development "> <transactionmanager type= "JDBC"/> <datasource type= "Pooled" > <property name= "Driver" Val Ue= "${driver}"/> <property name= "url" value= "${url}"/> <property name= "username" value= "${user" Name} "/> <property name= password" value= "${password}"/> </dataSource> &LT;/ENVIRONMENT&G
    T  <!--the second environment--> <environment id= "Publish" > <transactionmanager type= "JDBC"/> <datasource Type= "Pooled"/> </environment> </environments> </configuratiOn>

 

The first step is to introduce the XML file format, which is the DTD, which is to directly copy the templates provided by MyBatis

<! DOCTYPE configuration Public
    "-//mybatis.org//dtd Config 3.0//en"
    "http://mybatis.org/dtd/ Mybatis-3-config.dtd ">

Question 1
Properties function is to configure the corresponding properties file, resource is to specify the appropriate route, properties file inside we can configure the database driver, url, user name, password, etc., reference below, In this case, MyBatis will automatically read the following parameters, which you can refer to in the XML using ${}.

Driver = com.mysql.jdbc.Driver 
url=jdbc:mysql://localhost:3306/shop 
username=root 
password=123456

Question 2
typealiases Configure the alias under the specified path, we can configure a single alias
A single name <typealias type= "Com.model.User" alias= "user"/> so that the Com.model.User modified to alias user, the following does not need to write all the names, only need User to replace
Batch modification <package name= "Com.model"/> So that you can modify the class of a package, the default alias is the Entity class class name
Question 3
environments is a configuration database environment that can be configured with multiple environments, such as the development environment and the publishing environment, default
Environment Note that no s, representing an environment under environments, is differentiated by ID, so IDs must be unique
TransactionManager represents the connection database type, JDBC connects Java
DataSource configuration data source mode, pooled is the connection pool mode, the specific other mode can go to the official document, depending on the need to choose
Property This is the configuration database connection, name does not move, modify value= "Driver", here is used {} is read the top properties of the file inside the configuration, here attention to match the name can be read in the HA
3. Write mapper mapping SQL statements

This writes the Userdao load method, which reads a user based on the ID, which is equivalent to the public user load (int id) function
For MyBatis, there are two alternative #{} substitutions that automatically enclose quotes based on type, such as String type #{name} replaced with ' name '. The other is ${} replacement, which is replaced directly with the original format and will not add anything else

<?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>
  <select id= "load" parametertype= "int" resulttype= "user" >
    select * from User WHERE Id=#{id}
  </select>
</mapper>

The first step is to introduce a DTD header file to make XML file rules

Select Label, which indicates that the current is a SELECT statement
ID attribute, which is equivalent to a function name, referenced by ID
The ParameterType property, which represents the passed-in parameter type, can specify a base type, or a custom type, is a custom type, automatically calls its Get method, gets its properties
The Resulttype property, which returns a value type, can be directly custom typed and automatically calls the Set method to set the parameters of the query.
More properties are used in subsequent articles to say the same.
4. Call Mapper mapping

Before calling, you need to configure the mapping in Config.xml, and note that the XML configured here is the file path ha

<mappers>
  <mapper resource= "Com/model/user.xml"/>
</mappers>

Then write the test class

public static void Main (string[] args} {
    try {
      InputStream is = Resources.getresourceasstream ("config.xml"); Read configuration file
      sqlsessionfactory factory = new Sqlsessionfactorybuilder (). Build (IS);//create factory using configuration file
      sqlsession Session = Factory.opensession ()//Get session
      User user = Session.selectone (User.class.getName () + ". Load", 1); Call the Load function
      System.out.println (User.getnickname ());//output Nickname
      session.close ();//close Session
    } catch ( IOException e) {
      e.printstacktrace ();
    }
  }

Results:

5.Sqlsession Tool Class

Writing test classes like the above is too much trouble, put the sqlsession package to facilitate the use of the DAO layer

 package com.util;
Import org.apache.ibatis.io.Resources;
Import org.apache.ibatis.session.SqlSession;
Import Org.apache.ibatis.session.SqlSessionFactory;

Import Org.apache.ibatis.session.SqlSessionFactoryBuilder;
Import java.io.IOException;

Import Java.io.InputStream;
 /** * Created by nl101 on 2016/2/23.
  * * Public class Sessionutil {private static sqlsessionfactory factory= null; static {try {InputStream is = Resources.getresourceasstream ("config.xml");/read configuration file factory = new sqlsess
    Ionfactorybuilder (). Build (IS);//Use configuration file to create factory} catch (IOException e) {e.printstacktrace ();
  }/** * Get session * @return/public static sqlsession getsession () {return factory.opensession (); /** * Close Session * @param session/public static void CloseSession (Sqlsession sessions) {if session !=null) Session.close ();
  session = NULL; }
}

The above is the basic use of MyBatis, the following begins to encapsulate the DAO layer

Two. Package DAO

1.userdao.java

Public user load (int id) gets a User based on ID
I've already written it.
Public boolean Add (user user) to increase the number of users
XML code

 <!--add a user-->
  <insert id= "Add" parametertype= "user" >
    insert INTO User VALUES 
    (null,#{ Username},#{password},#{nickname},#{type})
  </insert>

Java code

/**
   /**
   * Add a user *
   @param user
   * @return true success
   /Public
  boolean Add (user user) {
    int isadd = 0;
    sqlsession session = Sessionutil.getsession ();
    try {
      Isadd = Session.insert (User.class.getName () + ". Add", User);
      Session.commit ()//Commit
    } catch (Exception e) {
      session.rollback ();//Submit failed rollback

    }finally {
      Sessionutil.closesession (session);
    System.out.println (isadd);
    Return isadd>0;
  }


public boolean delete (int id) Deletes a user

XML code

 <!--Delete a user-->
  <delete id= "delete" parametertype= "int" >
    delete from user WHERE Id=#{id}
  </delete>

Java code

/**
   * Delete User ID based on ID *
   @return True Success *
   /public boolean delete (int id) {
    int Isdelete = 0;
    sqlsession session = Sessionutil.getsession ();
    try {
      isdelete = Session.delete (User.class.getName () + ". Delete", id);
      Session.commit ();
    } catch (Exception e) {
      session.rollback ();//Failed to return
      System.out.println ("Delete user failed");
      E.printstacktrace ();
    } finally {
      sessionutil.closesession (session);
    }
    Return isdelete>0;
  }

Public boolean update (user) updates users

XML code

<!--Modify a user-->
  <update id= "Update" parametertype= "user" >
    update user SET Username=#{username}. Password=#{password},nickname=#{nickname},type=#{type} where Id=#{id}
  </update>

Java code

/** *
   Update user *
   @param user
   * @return true success
   /public
   boolean update (user user) {
    int isupdate = 0;
    sqlsession session = Sessionutil.getsession ();
    try {
      isupdate = Session.delete (User.class.getName () + ". Update", User);
      Session.commit ();
    } catch (Exception e) {
      session.rollback ();//Failed to return
      System.out.println ("Update user failed");
      E.printstacktrace ();
    } finally {
      sessionutil.closesession (session);
    }
    Return isupdate>0;
  }


Public user Login (string username, string password) determines whether a user exists

XML code

<!--user Login to Judge-->
  <select id= "Login" parametertype= "String" resulttype= "user" >
    select * from user WHERE Username=#{username}
  </select>

Java code

/**
   * To determine whether a user exists
   * @param username username
   * @param password Password
   * @return exists return user does not exist return
   NULL
  */ Public User Login (string username, string password) {
    user user = null;
    sqlsession session = Sessionutil.getsession ();
    try {
      user = Session.selectone (SOAPBinding.Use.class.getName () + ". Login", username);
      The user is null if the password is incorrect
      (!user.getpassword (). Equals (password)) {
        user = null;
      }

    } finally {
      Sessionutil.closesession (session);
    return user;
  }

Public Pager Find (String name,string sort,string order) paging

XML code:
Dynamic SQL is used here, and for dynamic SQL, the use of tags such as where,if,chose can refer to official documents
In addition, in MyBatis, the concept of NULL does not exist, for example, you pass a user=null, but replace it with a "null" string. This value is null

 <!--paging code-->
  <select id= "Find" parametertype= "Map" resulttype= "user" >
    select * from user
    < If test= "Name!=null" >where (username like #{name} or nickname like #{name}) </if> ORDER by
     ${sort} ${order}
   limit #{pagestart},#{pagesize}
  </select>
  <!--total number of paging records-->
  <select id= "Findcount" Parametertype= "Map" resulttype= "int" >
    select COUNT (*) from user
    <if test= "Name!=null" >where ( Username like #{name} or nickname like #{name}) </if>
  </select>

Java code: Overall or according to the previous article design of pagination

/** * According to the specified criteria paging query * @param name query criteria, NULL represents an unconditional * @param sort sort criteria, null represents sorted by ID * @param order sort criteria, null represents ascending * @return/Public pager<user> find (String name,string sort,string order) {int pagestart = Systemcontext. Getpagestart ()//paging start int pageSize = Systemcontext.getpagesize (),//Paging size pager<user> pagers = new PAGER&LT;&G
    t; ();
    map<string,object> maps = new hashmap<> ();
      if (Name!=null &&!name.equals ("")) {name = "%" +name+ "%";
    Maps.put ("name", name); } if (Sort==null | | sort.equals (")) {sort =" id ";//default sorted by ID} if (order==null | |
    Order.equals ("")) {order = "ASC";//Default sort} maps.put ("Sort", sort);
    Maps.put ("Order");
    Maps.put ("Pagestart", Pagestart);
    Maps.put ("PageSize", pageSize);
    sqlsession session = Sessionutil.getsession ();
    List<user> datas = null; try {datas = Session.selectlist (User.class.getName () + ". Find", maps);//Get record PagErs.setdatas (datas);
      Pagers.setpagesize (pageSize);
      Pagers.setpagestart (Pagestart); int totalrecord = Session.selectone (User.class.getName () + ". Findcount", maps);//Get total number of records Pagers.settotalrecord (
      Totalrecord);

    Pagers.setpageindex (pagestart/pagesize+1);
    finally {sessionutil.closesession (session);
  return pagers;

 }

Current project structure

The next article writes a generic Basedao to facilitate code writing. and continue to learn the use of MyBatis other attributes, thank you for your reading.

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.