Java-mybaits-00103-entry program native "search, increase, delete, change"

Source: Internet
Author: User

first, the need to achieve the following functions: query a user information based on user ID fuzzy query user Information list Add user update user Delete user two, specific steps 1. Add POM Reference 2. Add log4j.properties
# Global Logging configuration# development environment set to debug, production environment set to info or Errorlog4j.rootlogger=debug, stdout# Console Output...log4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.layout=  Org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%5p [%t]-%m%n
MyBatis uses log4j as the output log information by Default. 3.sqlmapconfig.xml Create the Sqlmapconfig.xml under classpath, as follows: Configure the operating environment for mybatis, data sources, transactions, and so On.
<?XML version= "1.0" encoding= "UTF-8"?><!DOCTYPE configurationpublic "-//mybatis.org//dtd Config 3.0//en" "http://mybatis.org/dtd/mybatis-3-config.dtd" ><Configuration>    <!--environments configuration will be abolished after the integration with spring -    <Environmentsdefault= "development">        <EnvironmentID= "development">            <!--using JDBC Transaction management -            <TransactionManagertype= "JDBC" />            <!--Database Connection Pool -            <DataSourcetype= "pooled">                < propertyname= "driver"value= "com.mysql.jdbc.Driver" />                < propertyname= "url"value= "jdbc:mysql://localhost:3306/mybatis?characterencoding=utf-8" />                < propertyname= "username"value= "root" />                < propertyname= "password"value= "root" />            </DataSource>        </Environment>    </Environments>    <mappers>        <MapperResource= "sqlmap/user.xml" />    </mappers></Configuration>
View CodeSqlmapconfig.xml is the mybatis core configuration file with the configuration content of the top file as the data source, transaction Management. 4, other PO class, mapper's writing See all codeHttps://github.com/bjlhx15/mybatisIii. Summary of Knowledge points 1.#{} and ${}#{}Represents a placeholder symbol, #{} receives input parameters, types can be simple types, pojo, hashmap.  If you receive a simple type, you can write value or other name in #{}. Receives the Pojo object value, through ognl, to read the property values in the object, through the Properties. properties ... Gets the object property value in the same way.${}  Represents a concatenation symbol that causes SQL injection, so it is not recommended to use ${}.  Receive input parameters, type can be simple type, pojo, hashmap.  If you receive a simple type, you can only write value in ${}. Receives the Pojo object value, through ognl, to read the property values in the object, through the Properties. properties ... Gets the object property value in the same way. 2.parameterType and resulttypeparametertype: Specifies the input parameter type, MyBatis gets the parameter value from the input object by OGNL stitching in Sql. resulttype: Specifies the output result type, MyBatis maps a row of record data for the SQL query results to resulttype objects of the specified type. 3.selectOne and Selectlistselectone indicate that a record is queried for Mapping. If using SelectOne can be implemented using SelectList can also be implemented (only one object in list). SelectList indicates that a list (multiple Records) is queried for mapping. If you use SelectList to query multiple records, you cannot use Selectone.  selectone queries a record and throws an exception if you query multiple records using Selectone: org.apache.ibatis.exceptions.TooManyResultsException:Expected One result (or Null) to being returned by SelectOne (), but found:3    at ORG.APACHE.IBATIS.SESSION.DEFAULTS.D  Namespace Namespace: namespace in Efaultsqlsession.selectone (defaultsqlsession.java:70) 4.mapper for isolating SQL Statements. Note: using Mapper Proxy method development, namespace compare important 5.sqlsession create using
Configuration file String resource = "sqlmapconfig.xml"; InputStream InputStream = Resources.getresourceasstream (resource);// Use Sqlsessionfactorybuilder to create Sqlsessionfactorysqlsessionfactory sqlsessionfactory from an XML configuration file = new Sqlsessionfactorybuilder (). Build (inputstream); Sqlsession sqlsession = Null;try {//create A DB session instance sqlsession   sqlsession = sqlsessionfactory.opensession ();   User user = Sqlsession.selectone ("test.finduserbyid", 1); //execute SQL   System.out.println (user);} Catch (Exception e) {   e.printstacktrace ();} finally {   if (sqlsession! = Null) {      sqlsession.close ();}   }
6.mysql Auto-increment PRIMARY Key
<InsertID= "insertuser"ParameterType= "cn.itcast.mybatis.po.User">       <!--Selectkey returns the primary key and needs to return -       <SelectkeyKeyproperty= "id"Order= "after"Resulttype= "java.lang.Integer">Select last_insert_id ()</Selectkey>INSERT INTO user (username,birthday,sex,address) values (#{username},#{birthday},#{sex},#{address});</Insert>
Adding the Selectkey implementation returns the primary key to keyproperty: which property of the returned primary key is stored in Pojo order:selectkey execution order, relative to the insert statement, Since the MySQL self-increment principle executes the INSERT statement before the primary key is generated, the execution order of the selectkey here is afterresulttype: what type of primary key is returned last_insert_id (): is the function of mysql, return auto _increment self-increment The new record ID Value. 7.Mysql using UUID to implement primary key
<InsertID= "insertuser"ParameterType= "cn.itcast.mybatis.po.User"><SelectkeyResulttype= "java.lang.String"Order= "before"Keyproperty= "id">Select UUID ()</Selectkey>INSERT INTO user (ID, username,birthday,sex,address) values (#{ID},#{username},#{birthday},#{s Ex},#{address})</Insert>
Note that the order used here is "before" using the MySQL UUID () function to generate the primary key, which needs to be modified in the table with the ID field type string and the length set to 35 bits.implementation Ideas:The primary key is first queried through the UUID () and the primary key is set to the user property, which is then entered into the SQL Statement. The execution UUID () statement order is executed in relation to the insert Statement. 8.Oracle using a sequence to generate a primary key to first customize a sequence and to generate a primary key, Selectkey uses the following:
<InsertID= "insertuser"ParameterType= "cn.itcast.mybatis.po.User"><SelectkeyResulttype= "java.lang.Integer"Order= "before"Keyproperty= "id">SELECT a custom Sequence. Nextval from DUAL</Selectkey>INSERT INTO user (id,username,birthday,sex,address) values (#{id},#{username},#{birthday},#{sex},#{address}) </Insert>
Note that the order used here is "before"

Java-mybaits-00103-entry program native "search, increase, delete, change"

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.