Optimization of mybatiscrud

Source: Internet
Author: User

We talked about all crud tests a few days ago. The following is an optimization of the crud example:
1. typealiases: In the usermapper. xml file in the example, you can see that when using the user type, you need to write the full qualified name of the user class. In the mybatis-config.xml, you can use the typealiases element to simplify this operation:
Add in mybatis-config.xml:
<Typealiases>
<Typealias type = "CD. itcast. mybatis. domain. User" alias = "user"/>
</Typealiases>
CD. itcast. mybatis. domain. the user has a simplified name: User. Then, you can use the user in the Mapper file to replace the CD. itcast. mybatis. domain. user, think about hibernate import.
The modified usermapper. xml file is as follows:
<Mapper namespace = "CD. itcast. mybatis. domain. usermapper">
<Insert id = "save" keyproperty = "ID" parametertype = "user" usegeneratedkeys = "true">
Insert into user (name, hiredate) values (# {name}, # {hiredate })
</Insert>

<Update id = "Update" parametertype = "user">
Update user set name =#{ name}, hiredate =#{ hiredate} Where ID =#{ ID}
</Update>

<Delete id = "delete" parametertype = "int">
Delete from user where ID =#{ ID}
</Delete>

<Select id = "get" parametertype = "int" resulttype = "user">
Select * from user where ID =#{ ID}
</SELECT>

<Select id = "list" resulttype = "user">
Select * from user
</SELECT>
</Mapper>
Simplified.

2. properties: we have said that the database connection information should be put into an additional. properties file. mybatis allows us to do this.
First, modify the mybatis-config.xml file:
<Environments default = "default">
<Environment id = "default">
<Transactionmanager type = "JDBC"/>
<Datasource type = "pooled">
<Property name = "driver" value = "$ {driverclass}"/>
<Property name = "url" value = "$ {URL}"/>
<Property name = "username" value = "$ {username}"/>
<Property name = "password" value = "$ {password}"/>
</Datasource>
</Environment>
</Environments>
The datasource configuration method of Lenovo spring is not difficult to understand.
There are three methods to configure the placeholder data source:
Method 1: In the build method of sqlsessionfactorybuilder, the method for passing in the properties object is also provided:
Public sqlsessionfactory build (inputstream, properties Properties)
The properties object after this method can be used as a parameter source in the mybatis-config.xml. Therefore, we can use:
Properties P = new properties ();
P. Load (this. getclass (). getclassloader (). getresourceasstream ("DB. properties ");
Define a DB. properties file under classpath:
Driverclass = com. MySQL. JDBC. Driver
Url = JDBC: mysql: // hibernate
Username = root
Password = Admin


The second way to use: if there is a tag such as properties in the mybatis-config.xml, we can define in the mybatis-config.xml:
<Properties>
<Property name = "driverclass" value = "com. MySQL. JDBC. Driver"/>
<Property name = "url" value = "JDBC: mysql: // hibernate"/>
<Property name = "username" value = "root"/>
<Property name = "password" value = "admin"/>
</Properties>
You can.

Method 3: introduce an external properties file in the properties element in the mybatis-config.xml:
<Properties resource = "DB. properties"/>
Add the DB. properties file to classpath.
The third and second methods can be used together, that is:
<Properties resource = "org/mybatis/example/config. properties">
<Property name = "username" value = "dev_user"/>
<Property name = "password" value = "f2fa3! 33 tyyg "/>
</Properties>

The priority of the three elements is: Properties imported by the code> properties loaded by the resource> properties defined in the properties element.

3. Abstract of mybatisutil:
In mybatis, the roles and status of sqlsessionfactory and sqlsession are very similar to sessionfactory and session, including thread security. That is
Sqlsessionfactory is thread-safe. You only need to create one data source for the entire application.
Sqlsession is thread unsafe, and the best method or thread is the life cycle.
Therefore, we can abstract a mybatisutil to provide sqlsession creation:
Public class mybatisutil {
Private Static sqlsessionfactory factory;

Static {
Try {
Factory = new sqlsessionfactorybuilder (). Build (Resources
. Getresourceasstream ("mybatis-config.xml "));
} Catch (exception e ){
E. printstacktrace ();
}
}

Public static sqlsession opensession (){
Return factory. opensession ();
}
}

4. mapper interface implementation
In the preceding test case, The namespace + ID name of the SQL statement to be called is input when the session method is called. This is not required. You can pass in only the ID. However, if there are multiple ID ing names with the same ID in the mybatis environment, an error is returned. Therefore, it is best to use namespace + id to call a method. However, when using namespace + id, it is easy to report an error because it is of the string type and is not checked. Therefore, mybatis provides a very good design method to avoid this problem, that is, the Mapper interface.
Compare with usermapper. for the definition of XML, we only need to create an interface. Note that the interface name and package must be the same as that of mapper. the namespace defined in XML is consistent, that is, an interface is created: CD. itcast. mybatis. domain. usermapper:
Package CD. itcast. mybatis. domain;
Public interface usermapper {
// Corresponding <insert id = "save" keyproperty = "ID" parametertype = "user">
Void save (User U );

// Corresponds to <update id = "Update" parametertype = "user">
Void Update (User U );

// Corresponds to <Delete id = "delete" parametertype = "long">
Void Delete (long ID );

// Corresponds to <select id = "get" parametertype = "long" resulttype = "user">
User get (long ID );

// Corresponds to <select id = "list" resulttype = "user">
List <user> List ();
}
The comments for each method should be well understood.
Use the Mapper interface. With the Mapper interface and the Mapper interface is placed at the specified position, we can write the test as follows:
Public class crudtest {
@ Test
Public void testsave (){
Sqlsession session = mybatisutil. opensession ();
Try {
User u = new user ();
U. setname ("itcast ");
U. sethiredate (new date ());
Usermapper mapper = session. getmapper (usermapper. Class );
Mapper. Save (U );
Session. Commit ();
} Finally {
Session. Close ();
}
}

@ Test
Public void testget (){
Sqlsession session = mybatisutil. opensession ();
Try {
Usermapper mapper = session. getmapper (usermapper. Class );
User u = Mapper. Get (2L );
System. Out. println (U );
} Finally {
Session. Close ();
}
}

@ Test
Public void testupdate (){
Sqlsession session = mybatisutil. opensession ();
Try {
User u = new user ();
U. setid (1l );
U. setname ("Update ");
U. sethiredate (new date ());
Usermapper mapper = session. getmapper (usermapper. Class );
Mapper. Update (U );
Session. Commit ();
} Finally {
Session. Close ();
}
}

@ Test
Public void testlist (){
Sqlsession session = mybatisutil. opensession ();
Try {
Usermapper mapper = session. getmapper (usermapper. Class );
List <user> US = Mapper. List ();
System. Out. println (US );
} Finally {
Session. Close ();
}
}

@ Test
Public void testdelete (){
Sqlsession session = mybatisutil. opensession ();
Try {
Usermapper mapper = session. getmapper (usermapper. Class );
Mapper. Delete (2L );
Session. Commit ();
} Finally {
Session. Close ();
}
}
}
The Code becomes very clear, and all types are required by interfaces.
How does mybatis do this?
Test:
@ Test
Public void testmapper (){
Sqlsession session = mybatisutil. opensession ();
Try {
Usermapper mapper = session. getmapper (usermapper. Class );
System. Out. println (Mapper. getclass (). getname ());
} Finally {
Session. Close ();
}
}
Print result:
$ Proxy4
Mybatis provides a dynamic proxy for the interface. When executing the method above the usermapper interface, you can find the corresponding usermapper by referring to the fully qualified name of the interface. XML: When executing each method on the interface, it is actually executing namespace + id. mybatis selects to call the appropriate session method to execute according to the elements of the defined method, and input parameters.
Using the Mapper interface is also very convenient to integrate Spring + mybatis. Because we can directly regard the Mapper interface as the DaO interface of domain.

Assume that the user object remains unchanged, but the name DBA in the name column of the corresponding user table is re-designed as username, then run the test again:
The name attribute is null. In this case, the restriction that mybatis directly uses resulttype indicates that the attribute name must be the same as the column name (the case can be different ). In this case, you must manually map data table columns and objects. First, modify the get method:
<Select id = "get" parametertype = "int" resultmap = "usermapping">
Select * from user where ID =#{ ID}
</SELECT>
Here, we can see that resulttype is removed, because resulttype can only convert the default object type. It is changed to resultmap here, which is actually called resultmapping for better understanding of hibernate children's shoes. Here I define the result set as a usering named usermapping. The following defines usermapping:
<Resultmap type = "user" id = "usermapping">
<ID property = "ID" column = "ID"/>
<Result property = "name" column = "username"/>
<Result property = "hiredate" column = "hiredate"/>
</Resultmap>
Resultmap defines a specific ORM ing method.
1, type: represents O, that is, the type of the final returned object
2. ID: Set a name for the ing. This name is the ID of the resultmap used in get or list.
3, ID/Result: ing of this property. For details, refer to hibernate's property. The difference between ID and result is that ID is generally used to map primary keys, which can increase the speed. result is generally used for common attributes.
After setting, you can get the object normally.
In mybatis, if only resulttype is used, it is equivalent to automatically creating a resultmap for mybatis, but this resultmap directly completes the ing of attributes and columns with the same name. Therefore, the place where mybatis truly completes the ing is in resultmap.

At this point, the single-object crud mybatis implementation is complete. We can see that in mybatis, most of the control details are still controlled by ourselves, especially SQL. Therefore, when we see the relationship between multiple objects, we must have this concept. mybatis will not consider the object crud for us like hibernate, all SQL statements should be controlled by ourselves. Therefore, in completing the configuration of the mybaits object relationship, we need to transform some inherent object-oriented ideas in hibernate. If Hibernate is mainly object-oriented and supplemented by links, in mybatis, it focuses on relational models. In other words, if the object model is poorly designed, it is easy to feel the difficulty of implementation.

 

 

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.