MyBatis Combat Tutorial (MyBatis in action), MyBatis Getting started to masterTags: MyBatis
This mybatis tutorial is also good: http://limingnihao.iteye.com/blog/781671
MyBatis
Directory (?) [-] MyBatis actual combat tutorial MyBatis in action one of the development environment to build mybatis real-World tutorial MyBatis in action two interface programming MyBatis actual course mybatis in action three implementation data deletion and modification MyBatis actual combat tutorial MyBatis in action Four to implement the query MyBatis actual combat tutorial MyBatis in action Five and SPRING3 integration with source MyBatis practical tutorial MyBatis in Action VI and Spring MVC Integration MyBatis actual combat tutorial MyBatis in Action VII implementation mybatis page source download MyBatis Practical tutorial MyBatis in action eight mybatis dynamic SQL statement MyBatis actual combat tutorial MyBatis in action nine MyBatis code generation tool use MyBatis sqlsessiondaosupport use with code download
Transferred from: http://www.yihaomen.com/article/java/302.htm
(Reader note: Actually this should be called a very basic primer, if you have seen hibernate, then this is very simple)
Written in front of this series: previously used Ibatis, this is the predecessor of MyBatis, at that time in the project, feel very good, more flexible than hibernate. Performance is better than hibernate. And also relatively lightweight, because at that time in the project, did not come and do a lot of notes. Then the project was over, and I didn't write a summary document. It's been a long time. But lately it's suddenly interesting to this ORM tool. This ORM tool is most likely to be used in the next project. So we have a refresher on mybatis, so we have this series of mybatis tutorials.
What is MyBatis
MyBatis is an excellent persistence layer framework that supports common SQL queries, stored procedures, and advanced mappings. MyBatis eliminates the manual setting of almost all JDBC code and parameters and the retrieval of the result set. MyBatis uses simple XML or annotations for configuration and raw mapping, mapping interfaces and Java POJOs (Plan old Java Objects, plain Java objects) to records in a database.
The basic idea of ORM tools
Whether it's used hibernate,mybatis or not, you can have one thing in common:
1. Get sessionfactory from the configuration file (usually in the XML configuration file).
2. Session generated by Sessionfactory
3. In the session to complete the deletion of data and other changes and transaction submissions.
4. Close the session after use is complete.
5. There is a mapping configuration file between the Java object and the database, usually an XML file.MyBatis Real-world tutorials (MyBatis in action): Development environment Building MyBatis development environment to build, select: Eclipse java EE version, MySQL 5.1, JDK 1.7,mybatis3.2.0.jar package. These software tools can be downloaded to the respective official website.
First, create a dynamic Web project named Mybaits.
1. At this stage, you can build a Java project directly, but generally you are developing Web projects, and this series of tutorials ends up being web-based, so you start with Web engineering.
2. Copy the Mybatis-3.2.0-snapshot.jar,mysql-connector-java-5.1.22-bin.jar to the Lib directory of the Web project.
3. Create MySQL test database and user table, note that the UTF-8 encoding is used here
Create a user table and insert a test data
Program code
Create TABLE ' user ' (
' id ' int (one) not NULL auto_increment,
' userName ' varchar DEFAULT NULL,
' Userage ' int (one) DEFAULT NULL,
' useraddress ' varchar ($) DEFAULT NULL,
PRIMARY KEY (' id ')
) Engine=innodb auto_increment=2 DEFAULT Charset=utf8;
Insert into ' user ' VALUES (' 1 ', ' Summer ', ' + ', ' shanghai,pudong ');
So far, the preparatory work has been completed. The following is the real configuration of the MyBatis project.
1. Create two source directories in MyBatis, respectively, SRC_USER,TEST_SRC, set up in the following way, right click on the Javaresource mouse button.
2. Set the MyBatis configuration file: Configuration.xml, create this file in the Src_user directory, as follows:
Program code
< 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>
<typeAliases>
<typealias alias= "User" type= "Com.yihaomen.mybatis.model.User"/>
</typeAliases>
<environments default= "Development" >
<environment id= "Development" >
<transactionmanager type= "JDBC"/>
<datasource type= "Pooled" >
<property name= "Driver" value= "Com.mysql.jdbc.Driver"/>
<property name= "url" value= "Jdbc:mysql://127.0.0.1:3306/mybatis"/>
<property name= "username" value= "root"/>
<property name= "password" value= "password"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource= "Com/yihaomen/mybatis/model/user.xml"/>
</mappers>
</configuration>
3. Create the Java class corresponding to the database and the mapping file.
Build the Package:com.yihaomen.mybatis.model under Src_user and create the User class under this package:
Program code
Package Com.yihaomen.mybatis.model;
public class User {
private int id;
Private String UserName;
Private String userage;
Private String useraddress;
public int getId () {
return ID;
}
public void setId (int id) {
This.id = ID;
}
Public String GetUserName () {
return userName;
}
public void Setusername (String userName) {
This.username = UserName;
}
Public String Getuserage () {
return userage;
}
public void Setuserage (String userage) {
This.userage = Userage;
}
Public String getuseraddress () {
return useraddress;
}
public void setuseraddress (String useraddress) {
this.useraddress = useraddress;
}
}
Also establish this User mapping file User.xml:
Program code
< 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 namespace= "Com.yihaomen.mybatis.models.UserMapper" >
<select id= "Selectuserbyid" parametertype= "int" resulttype= "User" >
SELECT * from ' user ' where id = #{id}
</select>
</mapper>
Below are the explanations for these configuration files:
1.configuration.xml is mybatis used to build sessionfactory, which mainly contains the database connection related things, as well as the Java class corresponding aliases, such as <typealias alias= "User" type = "Com.yihaomen.mybatis.model.User"/> This alias is very important, you in the specific class mapping, such as User.xml Resulttype is corresponding here. To be consistent, of course, there is a separate definition of the resulttype here, and then the other way around.
2. Configuration.xml inside the <mapper resource= "Com/yihaomen/mybatis/model/user.xml"/> is the XML configuration file that contains the class to be mapped.
3. In the User.xml file, the main definition is the various SQL statements, as well as the parameters of these statements, as well as the types to be returned.
Start testing
Build Com.yihaomen.test the package under the TEST_SRC source directory and set up test class tests:
Program code
Package com.yihaomen.test;
Import Java.io.Reader;
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 Com.yihaomen.mybatis.model.User;
public class Test {
private static Sqlsessionfactory sqlsessionfactory;
private static reader reader;
static{
try{
Reader = Resources.getresourceasreader ("Configuration.xml");
Sqlsessionfactory = new Sqlsessionfactorybuilder (). build (reader);
}catch (Exception e) {
E.printstacktrace ();
}
}
public static Sqlsessionfactory getsession () {
return sqlsessionfactory;
}
public static void Main (string[] args) {
sqlsession session = Sqlsessionfactory.opensession ();
try {
User user = (user) Session.selectone ("Com.yihaomen.mybatis.models.UserMapper.selectUserByID", 1);
System.out.println (User.getuseraddress ());
System.out.println (User.getusername ());
} finally {
Session.close ();
}
}
}
Now run this program, is not to get the results of the query. Congratulations, the environment is set up successfully, the second chapter, will be about the interface-based operation, add and delete changes.
The entire project directory structure is as follows:
Unless stated, the article is a door original, reproduced please specify the address of this article, thank you!
MyBatis Practical Course (MyBatis in action): Programming in the form of an interface
In the previous chapter, the ECLIPSE,MYBATIS,MYSQL environment has been set up, and a simple query has been implemented. Note that this is done using the sqlsession instance to directly execute the mapped SQL statement:
Session.selectone ("Com.yihaomen.mybatis.models.UserMapper.selectUserByID", 1)
In fact, there are simpler ways, and it's a better way. Using an interface that reasonably describes the parameters and the return value of the SQL statement (for example, Iuseroperation.class), it is now possible to get to that simpler, more secure code, without the error of string literals and conversions that are prone to occur. The following is a detailed procedure:
In the Src_user source directory under the establishment of Com.yihaomen.mybatis.inter this package, and the establishment of interface class Iuseroperation, the contents are as follows:
Program code
Package com.yihaomen.mybatis.inter;
Import Com.yihaomen.mybatis.model.User;
Public interface Iuseroperation {
Public User Selectuserbyid (int id);
}
Note that there is a method name in this Selectuserbyid that must correspond to the ID of the select configured in User.xml (<select id= "Selectuserbyid")
Rewrite test code
Program code
public static void Main (string[] args) {
sqlsession session = Sqlsessionfactory.opensession ();
try {
Iuseroperation Useroperation=session.getmapper (Iuseroperation.class);
User user = Useroperation.selectuserbyid (1);
System.out.println (User.getuseraddress ());
System.out.println (User.getusername ());
} finally {
Session.close ();
}
}
The entire engineering chart is now as follows:
Run the test program and you'll see the results.
Unless stated, the article is a door original, reproduced please specify the address of this article, thank you!
MyBatis Actual Combat tutorial (MyBatis in action) Three: to achieve data deletion and modification