How to use Universal Mapper

Source: Internet
Author: User

Integration method Please look at the above document, after integration, you can continue to read the document on this page.

1. Inherit the generic Mapper<T>, you must specify a generic <T>

For example, the following example:

Mapper<UserInfo//Other interfaces that must be handwritten ... }

Once inherited Mapper<T> , inheritance Mapper has Mapper<T> all the common methods.

2. Types of generics (entity classes) <T> must conform to requirements

Entity classes are converted according to the following rules and database tables, which are all annotations in JPA:

  1. The table name uses the class name by default, and the hump is underlined (only uppercase letters are UserInfo processed), as the default corresponding table name is user_info .

  2. Table names can be @Table(name = "tableName") specified using, and table names can be specified in this manner for non-conforming to the first default rule.

  3. Fields are the same as table fields by default, and the @Column table field defaults to the Java object's Field name hump to underline form.

  4. You can use @Column(name = "fieldName") a field name that specifies a rule that does not conform to 3rd

  5. @TransientYou can use annotations to ignore fields, and fields that add the annotations are not used as table columns.

  6. It is recommended that you have an @Id annotation as the primary key field, and you can have multiple @Id annotated fields as the Federated primary key.

  7. By default, if there are no fields with annotations in the entity class @Id , All fields are used as primary key fields (this is extremely inefficient ).

  8. entity Classes can be inherited and can be referenced to classes in the test code tk.mybatis.mapper.model.UserLogin2 .

  9. Because the base type, such as int as the Entity class field, has a default value of 0 and cannot be eliminated, the base type is not recommended in the entity class.

  10. @NameStyleAnnotations, which are used to configure the conversion between the object name/field and the Table name/field, which takes precedence over the global configuration style and optional values:

    • normal: Use entity class name/attribute name as table name/field name
    • camelhump: This is the default value , the hump is converted to an underscore form
    • uppercase: Convert to uppercase
    • lowercase: Convert to lowercase

By using the mapper dedicated MyBatis generator plug-in, you can directly generate an entity class that conforms to the requirements annotated.

Emphasis is placed on @TransientAnnotations

Many people frequently make mistakes on this issue because they do not look closely at the documentation.

If your entity class contains fields that are not in a database table, you need to annotate this field so that the @Transient Universal Mapper does not treat the attributes of the labels as table fields when handling a single table operation!

3. Primary key policy (only for InsertMethod

Universal Mapper also provides sequence (Oracle supported), UUID (Arbitrary database, field length 32), primary key self-increment (similar to mysql,hsqldb) three ways, where sequence and UUID can be configured multiple, primary key auto-increment can only configure one .

Since MySQL self-increment primary key is most commonly used, so this is the simplest way to start the configuration.

1. @GeneratedValue(generator = "JDBC")
@Id@GeneratedValue("JDBC")Id;     

This causes MyBatis to use the JDBC Getgeneratedkeys method to remove the primary key generated internally by the database (for example, an auto-increment field for a relational database management system such as MySQL and SQL Server).
This scenario corresponds to the XML that resembles the following:

id=usegeneratedkeys=keyproperty="id"> INSERT into Author (Username,password,email,bio) VALUES (#{username},#{password},#{email},#{bio})</insert>    
2. @GeneratedValue(strategy = GenerationType.IDENTITY)

This annotation applies to the case of a primary key increment and supports the following databases:

    • DB2 :   VALUES identity_val_local ()
    • MYSQL :   select last_insert_id ()
    • SQL Server :   SELECT scope_identity ()
    • CLOUDSCAPE :   VALUES identity_val_local ()
    • DERBY :   VALUES identity_val_local ()
    • HSQLDB :   call IDENTITY ()
    • SYBASE :   SELECT @ @IDENTITY
    • DB2_MF :   SELECT identity_val_local () from SYSIBM. SYSDUMMY1
    • INFORMIX :   Select Dbinfo (' Sqlca.sqlerrd1 ') from Systables where tabid=1
    • jdbc : This causes MyBatis to use the Getgeneratedkeys method of JDBC to remove the primary key generated internally by the database (for example: MySQL and An auto-increment field for a relational database management system such as SQL Server).

Use the GenerationType.IDENTITY parameter values that you want to configure in the global configuration IDENTITY , and you need to configure the properties based on the number of libraries ORDER .

Examples are as follows:

is not limited to the field of the @Id annotation, but only one of the entity classes can exist ( only one in the inheritance relationship)@Id@GeneratedValue(  GenerationType.  IDENTITY)ID;        

The corresponding XML form is:

Id= "insertauthor">    keyproperty=resulttype=order="after"</selectKey> INSERT into Author (ID, username, password, email,bio, favourite_section) VALUES (#{id}, #{username}, #{password}, #{email }, #{bio}, #{favouritesection,jdbctype=varchar})</insert>       

Note that <selectKey> the IDENTITY contents of the parameter values correspond to the SQL of the database

3. @GeneratedValue(generator = "UUID")
Can be used for any string type longer than 32 bits of the field @GeneratedValue("UUID")username;     

The field does not write back. This situation corresponds to XML similar to the following:

id="Insertauthor">  name=value=/> INSERT into Author (ID, username, password, email,bio, Favourite_section) VALUES (#{id}, #{username_bind}, #{password}, #{email}, #{bio}, #{favouritesection,jdbctype= VARCHAR})</insert>     

Note: This method cannot be written back, if you want to write back, see the general Mapper UUID Simple Example

4.Oracle using sequences
@Id@GeneratedValue(generationtype.  IDENTITY,"select Seq_id.nextval from Dual")ID;         

When using the Oracle sequence, you also need to configure:

Name=value="before"/>  

Because you need to get the sequence value before inserting the database, you will be given an error.
This situation is similar to the following for XML:

id="Insertauthor">keyproperty=resulttype=order="before"> select Seq_ Id.nextval from dual</selectkey>insert to Author (ID, username, password, email,bio, favourite_section) VALUES (#{id}, #{username}, #{password}, #{email}, #{bio}, #{favouritesection,jdbctype=varchar})</insert> 
4. Add the inherited mapper interface to the MyBatis configuration in a non-spring project in the MyBatis configuration file, such as:
<mappers>  class=/>  class=class=/></mappers> 
How spring is configured

If you configure the Mapper interface in spring, you do not need to configure it as above, only the following configuration of the scan mapper interface is required:

class="Tk.mybatis.spring.mapper.  Mapperscannerconfigurer">  name="basepackagevalue=" Com.isea533.mybatis.mapper "/></bean>       

In addition, because the common interface has a top-level interface, you can also configure it in the following ways:

class= "tk.mybatis.spring.mapper.MapperScannerConfigurer">  name="basepackage value= "com.**.mapper"name="markerinterfacevalue=" Tk.mybatis.mapper.common.Mapper "/></bean>        

After this configuration, directly inherit Mapper The interface will be scanned, basePackage you can configure a larger range.

If you want to use generic injection in Spring4, you also need to include Mapper<T> the package that you are using, for more details, see Use generic mapper in Spring4.

5. Use in code

For example, here's a simple example:

SqlsessionSqlsession=Mybatishelper.Getsqlsession();Try{//Get Mapper UserinfomapperMapper=sqlsession.Getmapper(Userinfomapper.Class);UserInfoUserInfo=NewUserInfo();UserInfo.Setusername("abel533");UserInfo.SetPassword("123456");UserInfo.Setusertype("2");UserInfo.Setemail("[Email protected]");Add a new piece of dataAssert.Assertequals(1,Mapper.Insert(UserInfo));ID write-back, not emptyAssert.Assertnotnull(UserInfo.GetId());//6 is the current ID assert. Assertequals (6 (int ) userinfo.//delete new data by primary key assert. (1,mapper. Deletebyprimarykey (userinfo} finally {sqlsession. Close ()              

Another example:

SqlsessionSqlsession=Mybatishelper.Getsqlsession();Try{Get MapperCountrymapperMapper=Sqlsession.Getmapper(Countrymapper.Class);Total queriesAssert.Assertequals(183,Mapper.SelectCount(NewCountry()));Enquiry 100CountryCountry=Mapper.Selectbyprimarykey(100);Delete based on primary keyAssert.Assertequals(1,Mapper.Deletebyprimarykey(100//total number of queries assert. (182mapper.selectcount (new country ())); //insert assert. (1mapper. Insert (country} finally {sqlsession. Close ()              

Attached: Spring Use related

Inject Mapper inherited interfaces directly where they are needed, with no difference in general usage.

6. Other

If your entity inherits the map, you may need to convert the results of the database query from uppercase to Camel, and you can use the following interceptors:

Camehumpinterceptor-map The result of the key to the hump type

Http://git.oschina.net/free/Mybatis_Utils/tree/master/CameHumpMap

Http://git.oschina.net/free/Mapper/blob/master/wiki/mapper3/3.Use.md

How to use Universal Mapper

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.