MyBatis Quick Start (simple and easy to understand) _java

Source: Internet
Author: User

Introduction of 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 encapsulation of the result set.

MyBatis can use simple XML or annotations for configuration and raw mappings, mapping interfaces and Java Pojo (Plain old Java Objects, normal Java objects) to records in the database.

JDBC-> dbutils (automatic encapsulation)-> MyBatis-> Hibernate

MyBatis is to write SQL in XML and then access the database.

Second, MyBatis Quick Start

2.1. New Java Project

Add mybatis and MySQL driver Jar:mybatis-3.1.1.jar,mysql-connector-java-5.1.7-bin.jar

2.2. New Table

Create database MyBatis;
Use MyBatis;
CREATE table users (ID int primary key auto_increment, name varchar (), age int);
Insert into users (name,age) VALUES (' Tom ', a);
Insert into the users (name, age) VALUES (' Jack ', 11);

2.3. Add the MyBatis profile Conf.xml

<?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>
<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://localhost:3306/mybatis "/>
<property name=" username "value=" root "/> <property name="
password "value=" root "/>
</dataSource>
</environment>
</environments>
</configuration>

2.4. Define the entity class for the table

public class User {
private int id;
private String name;
private int age;
Get,set Method
}

2.5. Define SQL mapping files that manipulate the users table Usermapper.xml

<?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.atguigu.mybatis_test.test1.userMapper" >
<select id= "GetUser" int "
resulttype=" Com.atguigu.mybatis_test.test1.User ">
select * from users where id=#{id}
</ Select>
</mapper>

2.6. Registering usermapper.xml files in the Conf.xml file

<mappers>
<mapper resource= "Com/atguigu/mybatis_test/test1/usermapper.xml"/>
</mappers >

2.7. Writing test code: Executing a defined SELECT statement

public class Test {public
static void Main (string[] args) throws IOException {
String resource = "Conf.xml";
Loading the MyBatis configuration file (It also loads the associated mapping file)
Reader reader = resources.getresourceasreader (Resource);
Building sqlsession Factory
sqlsessionfactory sessionfactory = new Sqlsessionfactorybuilder (). build (reader);
Create Sqlsession
sqlsession session = Sessionfactory.opensession () that can execute SQL in the mapping file;
Mapping SQL's identity string string
statement = "Com.atguigu.mybatis.bean.userMapper" + ". Selectuser";
Execute query returns the SQL
user user = Session.selectone (statement, 1) of a unique User object;
SYSTEM.OUT.PRINTLN (user);
}

Third, the operation of the Users table crud

Implementation of 3.1.xml

3.1.1. Define SQL Mapping XML file:

<insert id= "Insertuser" parametertype= "Com.atguigu.ibatis.bean.User" >
insert into the users (name, age) VALUES ( #{name}, #{age});
</insert>
<delete id= "deleteuser" parametertype= "int" >
delete from users where Id=#{id}
< /delete>
<update id= "UpdateUser" parametertype= "Com.atguigu.ibatis.bean.User" >
update users set Name=#{name},age=#{age} where Id=#{id}
</update>
<select id= "Selectuser" parametertype= "int" Resulttype= "Com.atguigu.ibatis.bean.User" >
select * from users where id=#{id}
</select>
<select id= "Selectallusers" resulttype= "Com.atguigu.ibatis.bean.User" >
select * from users
</ Select>

3.1.2. Register this mapping file in Config.xml

<mapper resource= "Com/atguigu/ibatis/bean/usermapper.xml"/>

3.1.3. Calling in DAO

Public User Getuserbyid (int id) {
sqlsession session = Sessionfactory.opensession ();
User user = Session.selectone (uri+ ". Selectuser", id);
return user;
}

3.2. Implementation of annotations

3.2.1. Interface for defining SQL mappings

Public interface Usermapper {
@Insert (Insert to users (name, age) VALUES (#{name}, #{age})) Public
int Insertuser (user user);
@Delete (' Delete from Users where Id=#{id} ') public
int Deleteuserbyid (int id);
@Update ("Update users set Name=#{name},age=#{age} where Id=#{id}") Public
int updateuser (user user);
@Select (' Select * from users where id=#{id} ') public
User Getuserbyid (int id);
@Select (' Select * from users ') public
list<user> Getalluser ();
}

3.2.2. Register this mapping interface in config

<mapper class= "Com.atguigu.ibatis.crud.ano.UserMapper"/>

3.2.3. Calling in DAO

Public User Getuserbyid (int id) {
sqlsession session = Sessionfactory.opensession ();
Usermapper mapper = Session.getmapper (usermapper.class);
User user = Mapper.getuserbyid (ID);
return user;
}

Four, some can optimize the place

4.1. The configuration of the connection database can be placed separately in a properties file.

# # db.properties<br>
<properties resource= "db.properties"/> <property
"name=" value = "${driver}"/>
<property name= "url" value= "${url}"/> <property name= "username" value= "${"
Username} "/>
<property name= password" value= "${password}"/>

4.2. Define aliases for entity classes to simplify references in SQL mapped XML files

<typeAliases>
<typealias type= "Com.atguigu.ibatis.bean.User" alias= "_user"/>
</ Typealiases>

4.3. Can add log4j configuration file under SRC, print log information

1. Add Jar:

Log4j-1.2.16.jar

2.1. Log4j.properties (Mode i)

Log4j.properties,
log4j.rootlogger=debug, Console
#Console
log4j.appender.console= Org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.patternlayout
log4j.appender.console.layout.conversionpattern=%d [%t]%-5p [%c]-%m%n
log4j.logger.java.sql.resultset=info
log4j.logger.org.apache=info
Log4j.logger.java.sql.connection=debug
Log4j.logger.java.sql.statement=debug
Log4j.logger.java.sql.preparedstatement=debug

2.2. Log4j.xml (Mode II)

<?xml version= "1.0" encoding= "UTF-8"?> <!
DOCTYPE log4j:configuration SYSTEM "Log4j.dtd" >
<log4j:configuration xmlns:log4j= "http://" jakarta.apache.org/log4j/">
<appender name=" STDOUT "class=" Org.apache.log4j.ConsoleAppender ">
<layout class= "Org.apache.log4j.PatternLayout" >
<param name= "Conversionpattern" value= "%-5p%d{ 
Mm-dd hh:mm:ss,sss}%m (%f:%l) \ n "/>
</layout>
</appender> <logger name=
" java.sql " >
<level value= "Debug"/>
</logger>
<logger name= "Org.apache.ibatis" >
<level value= "Debug"/>
</logger>
<root>
<level value= "Debug"/>
< Appender-ref ref= "STDOUT"/>
</root>
</log4j:configuration>

Resolving conflicts between field names and entity class property names

5.1. Prepare tables and fields

CREATE TABLE orders (
order_id INT PRIMARY KEY auto_increment,
order_no VARCHAR),
order_price FLOAT
);
INSERT into orders (Order_no, Order_price) VALUES (' aaaa ',);
INSERT into orders (Order_no, Order_price) VALUES (' bbbb ',);
INSERT into orders (Order_no, Order_price) VALUES (' CCCC ', 22);

5.2. Define Entity classes

public class Order {
private int id;
Private String OrderNo;
private float price;

5.3. Implementation of Getorderbyid (ID) query:

Way one: By defining aliases in SQL statements

<select id= "Selectorder" parametertype= "int" resulttype= "_order" >
select order_id ID, order_no orderNo, Order_price Price from Orders where Order_id=#{id}
</select>

Mode two: Through <resultMap>

<select id= "Selectorderresultmap" parametertype= "int" resultmap= "Orderresultmap" >
select * FROM Orders Where Order_id=#{id}
</select>
<resultmap type= "_order" id= "Orderresultmap" >
<id property= "id" column= "order_id"/>
<result property= "OrderNo" column= "Order_no"/>
<result property= "Price" column= "Order_price"/>
</resultMap>

VI. implementation of relational table query

6.1. One-to-one correlation

6.1.1. Ask for a demand

Query class information According to class ID (with teacher's information)

6.1.2. Create tables and data

CREATE TABLE Teacher (
t_id INT PRIMARY KEY auto_increment,
t_name VARCHAR)
;
CREATE TABLE Class (
c_id int PRIMARY KEY auto_increment,
c_name VARCHAR (),
teacher_id int
);
ALTER TABLE class ADD CONSTRAINT fk_teacher_id FOREIGN KEY (teacher_id) REFERENCES teacher (t_id); 
INSERT into teacher (t_name) VALUES (' LS1 ');
INSERT into teacher (t_name) VALUES (' LS2 ');
INSERT into Class (C_name, teacher_id) VALUES (' bj_a ', 1);
INSERT into Class (C_name, teacher_id) VALUES (' Bj_b ', 2);

6.1.3. Define Entity classes:

public class Teacher {
private int id;
private String name;
public class Classes {
private int id;
private String name;
Private Teacher Teacher;
}

6.1.4. Define SQL Mapping File Classmapper.xml

&lt;!--: nested results: Using nested result mappings to handle a subset of duplicate federated results SELECT * from class C, teacher T,student s WHERE c.teacher_id=t.t_id and c.c_id= s.class_id and c.c_id=1--&gt; &lt;select id= "GETCLASS3" parametertype= "int" resultmap= "CLASSRESULTMAP3" &gt; select * From class C, teacher T,student s where c.teacher_id=t.t_id and c.c_id=s.class_id and C.c_id=#{id} &lt;/select&gt; &lt;res Ultmap type= "_classes" id= "ClassResultMap3" &gt; &lt;id property= "id" column= "c_id"/&gt; &lt;result "name" column= "C_name"/&gt; &lt;association property= "teacher" column= "teacher_id" javatype= "_teacher" &gt; &lt;id property= "id" column= "t_id"/&gt; &lt;result property= "name" column= "T_name"/&gt; &lt;/association&gt; &lt;!-- OFTYPE specifies the object type in the students collection--&gt; &lt;collection property= "Students" oftype= "_student" &gt; &lt;id property= "id" column=
"s_id"/&gt; &lt;result property= "name" column= "S_name"/&gt; &lt;/collection&gt; &lt;/resultMap&gt; &lt;!--
Mode two: Nested query: Returns the expected complex type SELECT * from class WHERE c_id=1 by executing another SQL mapping statement; SELECT * FROM Teacher where T_id=1//1 is the teacher_id value of the last query SELECT * FROM student WHERE class_id=1//1 is the value of the c_id field that the first query obtains--&gt; ECT id= "GETCLASS4" parametertype= "int" resultmap= "CLASSRESULTMAP4" &gt; select * from class where C_id=#{id} &lt;/select&
Gt &lt;resultmap type= "_classes" id= "CLASSRESULTMAP4" &gt; &lt;id property= "id" column= "c_id"/&gt; &lt;result "property=" Name "column=" C_name "/&gt; &lt;association property=" teacher "column=" teacher_id "javatype=" _teacher "select=" GetTeacher2 "&gt;&lt;/association&gt; &lt;collection property=" Students "oftype=" _student "column=" c_id "select=" Getstudent "&gt;&lt;/collection&gt; &lt;/resultMap&gt; &lt;select id=" getTeacher2 "parametertype=" int "resulttype=" _ Teacher "&gt; SELECT t_id ID, t_name name from Teacher WHERE t_id=#{id} &lt;/select&gt; &lt;select id=" Getstudent "Paramete rtype= "int" resulttype= "_student" &gt; SELECT s_id ID, s_name name from Student WHERE Class_id=#{id} &lt;/select&gt;

6.1.5. Test

@Test public
void Testoo () {
sqlsession sqlsession = factory.opensession ();
Classes C = Sqlsession.selectone ("Com.atguigu.day03_mybatis.test5.OOMapper.getClass", 1);
System.out.println (c);
}
@Test public
void TestOO2 () {
sqlsession sqlsession = factory.opensession ();
Classes C = Sqlsession.selectone ("Com.atguigu.day03_mybatis.test5.OOMapper.getClass2", 1);
System.out.println (c);
}

6.2. A One-to-many Association

6.2.1. Ask for a demand

According to CLASSID query corresponding class information, including students, teachers

6.2.2. Create tables and data:

CREATE TABLE Student (
s_id int PRIMARY KEY auto_increment,
s_name VARCHAR (),
class_id int
);
INSERT into student (S_name, class_id) VALUES (' Xs_a ', 1);
INSERT into student (S_name, class_id) VALUES (' Xs_b ', 1);
INSERT into student (S_name, class_id) VALUES (' Xs_c ', 1);
INSERT into student (S_name, class_id) VALUES (' Xs_d ', 2);
INSERT into student (S_name, class_id) VALUES (' Xs_e ', 2);
INSERT into student (S_name, class_id) VALUES (' Xs_f ', 2);

6.2.3. Define Entity classes

public class Student {
private int id;
private String name;
public class Classes {
private int id;
private String name;
Private Teacher Teacher;
Private list<student> students;
}

6.2.4. Define SQL Mapping File Classmapper.xml

&lt;!--: nested results: Using nested result mappings to handle a subset of duplicate federated results SELECT * from class C, teacher T,student s WHERE c.teacher_id=t.t_id and c.c_id= s.class_id and c.c_id=1--&gt; &lt;select id= "GETCLASS3" parametertype= "int" resultmap= "CLASSRESULTMAP3" &gt; select * From class C, teacher T,student s where c.teacher_id=t.t_id and c.c_id=s.class_id and C.c_id=#{id} &lt;/select&gt; &lt;res Ultmap type= "_classes" id= "ClassResultMap3" &gt; &lt;id property= "id" column= "c_id"/&gt; &lt;result "name" column= "C_name"/&gt; &lt;association property= "teacher" column= "teacher_id" javatype= "_teacher" &gt; &lt;id property= "id" column= "t_id"/&gt; &lt;result property= "name" column= "T_name"/&gt; &lt;/association&gt; &lt;!-- OFTYPE specifies the object type in the students collection--&gt; &lt;collection property= "Students" oftype= "_student" &gt; &lt;id property= "id" column=
"s_id"/&gt; &lt;result property= "name" column= "S_name"/&gt; &lt;/collection&gt; &lt;/resultMap&gt; &lt;!--
Mode two: Nested query: Returns the expected complex type SELECT * from class WHERE c_id=1 by executing another SQL mapping statement; SELECT * FROM Teacher where T_id=1//1 is the teacher_id value of the last query SELECT * FROM student WHERE class_id=1//1 is the value of the c_id field that the first query obtains--&gt; ECT id= "GETCLASS4" parametertype= "int" resultmap= "CLASSRESULTMAP4" &gt; select * from class where C_id=#{id} &lt;/select&
Gt &lt;resultmap type= "_classes" id= "CLASSRESULTMAP4" &gt; &lt;id property= "id" column= "c_id"/&gt; &lt;result "property=" Name "column=" C_name "/&gt; &lt;association property=" teacher "column=" teacher_id "javatype=" _teacher "select=" GetTeacher2 "&gt;&lt;/association&gt; &lt;collection property=" Students "oftype=" _student "column=" c_id "select=" Getstudent "&gt;&lt;/collection&gt; &lt;/resultMap&gt; &lt;select id=" getTeacher2 "parametertype=" int "resulttype=" _ Teacher "&gt; SELECT t_id ID, t_name name from Teacher WHERE t_id=#{id} &lt;/select&gt; &lt;select id=" Getstudent "Paramete rtype= "int" resulttype= "_student" &gt; SELECT s_id ID, s_name name from Student WHERE Class_id=#{id} &lt;/select&gt;

6.2.5. Test

@Test public
void Testom () {
sqlsession sqlsession = factory.opensession ();
Classes C = Sqlsession.selectone ("Com.atguigu.day03_mybatis.test5.OOMapper.getClass3", 1);
System.out.println (c);
}
@Test public
void TestOM2 () {
sqlsession sqlsession = factory.opensession ();
Classes C = Sqlsession.selectone ("Com.atguigu.day03_mybatis.test5.OOMapper.getClass4", 1);
System.out.println (c);
}

VII. dynamic SQL and fuzzy query

7.1. Demand

Multi-Criteria query user (name fuzzy matching, age at the specified minimum to the maximum value).

7.2. Prepare database and tables

CREATE TABLE D_user ( 
ID int primary key auto_increment, 
name varchar (), age
int (3)
);
Insert into D_user (name,age) VALUES (' Tom ', a); 
Insert into D_user (name,age) VALUES (' Bob '); 
Insert into D_user (name,age) VALUES (' Jack ', a);
7.3.ConditionUser (Query Condition entity Class)
private String name;
private int minage;
private int maxage;

7.4.User Table entity class

private int id;
private String name;
private int age;

7.5.usermapper.xml (mapping file)

<?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.atguigu.day03_mybatis.test6.userMapper" >
<select id= "GetUser" Parametertype= "Com.atguigu.day03_mybatis.test6.ConditionUser" resulttype= "Com.atguigu.day03_mybatis.test6.User" >
SELECT * from D_user where age>=#{minage} and Age<=#{maxage}
<if test= ' name!= '%null% ' >and Name like #{name}</if>
</select>
</mapper>

7.6.UserTest (Test)

public class Usertest {public
static void Main (string[] args) throws IOException {
Reader reader = Resources.getr Esourceasreader ("Conf.xml");
Sqlsessionfactory sessionfactory = new Sqlsessionfactorybuilder (). build (reader);
Sqlsession sqlsession = Sessionfactory.opensession ();
String statement = "Com.atguigu.day03_mybatis.test6.userMapper.getUser";
list<user> list = sqlsession.selectlist (statement, New Conditionuser ("%a%", 1,));
SYSTEM.OUT.PRINTLN (list);
}

Dynamic SQL tags available in the MyBatis

Viii. Calling stored Procedures

8.1. Demand is presented

Query gets the number of males or females, if the incoming is 0 for females otherwise it is male

8.2. Prepare database tables and stored procedures:

CREATE TABLE P_user ( 
ID int primary key auto_increment, 
name varchar (),
sex char (2)
);
Insert into P_user (name,sex) VALUES (' A ', "male"); 
Insert into P_user (name,sex) VALUES (' B ', ' female '); 
Insert into P_user (name,sex) VALUES (' C ', ' Male '); 
#创建存储过程 (Inquiries get the number of males or females, if the incoming is 0 female otherwise male)
DELIMITER $
CREATE PROCEDURE mybatis.ges_user_count (in sex_id INT, Out User_count INT)
BEGIN 
IF sex_id=0 THEN
SELECT Count (*) from Mybatis.p_user WHERE p_user.sex= ' female ' into u Ser_count;
ELSE
SELECT COUNT (*) from Mybatis.p_user WHERE p_user.sex= ' man ' into User_count;
End IF;
End
$
#调用存储过程
DELIMITER;
SET @user_count = 0;
Call Mybatis.ges_user_count (1, @user_count);
SELECT @user_count;

8.3. Create entity classes for a table

public class User {
private String ID;
private String name;
Private String sex;
}

8.4.usermapper.xml

<mapper namespace= "Com.atguigu.mybatis.test7.userMapper" >
<!--
query to get the number of males or females, if the incoming is 0 on the female otherwise it's male. Call
Mybatis.get_user_count (1, @user_count);
-->
<select id= "GetCount" statementtype= "callable" parametermap= "Getcountmap" > Call
mybatis.get_ User_count (?,?)
</select>
<parametermap type= "Java.util.Map" id= "Getcountmap" >
<parameter property= "sex_id" "Mode=" in "jdbctype=" integers "/> <parameter property=" User_count "mode=" Out
"jdbctype=" integer "/>
</parameterMap>
</mapper>

8.5. Test

map<string, integer> parammap = new hashmap<> ();
Parammap.put ("sex_id", 0);
Session.selectone (statement, parammap);
Integer UserCount = Parammap.get ("User_count");
System.out.println (UserCount);

Nine, MyBatis cache

9.1. Understanding MyBatis Caching

As with most persistence layer frameworks, MyBatis also provides support for first-level caching and level two caching

1. First-level caching: The HashMap local cache based on Perpetualcache, whose storage scope is session, and when session flush or close, all caches in the session are emptied.

2. The level two cache is the same as the first-level cache, and is Perpetualcache,hashmap stored by default, except that its storage scope is Mapper (Namespace), and a storage source, such as Ehcache, can be customized.

3. For the caching data update mechanism, when the c/u/d operation of a scope (cache session/level two cache namespaces) is performed, the cache in all select under the default scope is clear.

9.2.mybatis Cache Level

9.2.1. According to task query

The corresponding user record object is queried based on the ID.

9.2.2. Prepare database tables and data

CREATE TABLE c_user (
ID int PRIMARY KEY auto_increment,
NAME VARCHAR, age
INT
);
INSERT into C_user (NAME, age) VALUES (' Tom ',);
INSERT into C_user (NAME, age) VALUES (' Jack ', 11);

9.2.3. Create entity classes for a table

public class User implements serializable{
private int id;
private String name;
private int age;

9.2.4.usermapper.xml

<?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.atguigu.mybatis.test8.userMapper" >
<select id= "GetUser" parametertype= "int" Resulttype= "_cuser" >
select * from C_user where id=#{id}
</select>
<update id= "UpdateUser" Parametertype= "_cuser" >
update c_user set
Name=#{name}, Age=#{age} where Id=#{id}
</update>
</mapper>

9.2.5. Test

 * * First-level cache: Also on session-level caching (default open)/@Test public void TestCache1 () {sqlsession session =
Mybatisutils.getsession ();
String statement = "Com.atguigu.mybatis.test8.userMapper.getUser";
User user = Session.selectone (statement, 1);
SYSTEM.OUT.PRINTLN (user);
* * First-level cache will be used by default/* user = Session.selectone (statement, 1);
SYSTEM.OUT.PRINTLN (user); * * * 1.
Must be the same session, if the session object has been close () it is not possible to use the */* session = Mybatisutils.getsession ();
user = Session.selectone (statement, 1);
SYSTEM.OUT.PRINTLN (user); * * * 2.
The query condition is the same as */* user = Session.selectone (statement, 2);
SYSTEM.OUT.PRINTLN (user); * * * 3.
No Session.clearcache () cleanup Cache/* Session.clearcache ();
user = Session.selectone (statement, 2);
SYSTEM.OUT.PRINTLN (user); * * * 4. No additions or deletions have been performed (these operations will clean the cache) * * * session.update ("Com.atguigu.mybatis.test8.userMapper.updateUser", New User (2, "user")
23));
user = Session.selectone (statement, 2);
SYSTEM.OUT.PRINTLN (user); */
}

9.3.MyBatis Level Two cache

9.3.1. Add a <cache> in Usermapper.xml

<mapper namespace= "Com.atguigu.mybatis.test8.userMapper" >
<cache/>

9.3.2. Test


* * Test level Two cache
/@Test public
void TestCache2 () {
String statement = " Com.atguigu.mybatis.test8.userMapper.getUser ";
sqlsession session = Mybatisutils.getsession ();
User user = Session.selectone (statement, 1);
Session.commit ();
System.out.println ("user=" +user);
Sqlsession Session2 = Mybatisutils.getsession ();
user = Session2.selectone (statement, 1);
Session.commit ();
System.out.println ("user2=" +user);
}

9.3.3. Supplementary notes

1. All SELECT statements in the mapping statement file will be cached.

2. All insert,update and DELETE statements in the mapping statement file refresh the cache.

3. The cache is retracted using least recently Used (LRU, least recently used) algorithm.

4. The cache is refreshed according to the specified time interval.

5. The cache will store 1024 objects

<cache
eviction= "FIFO"//recycling strategy for advanced first out
flushinterval= "60000"//automatic refresh time 60s
size= "512"//MAX cache 512 Reference objects
readonly= "true"/>//Read Only

X. Spring Integrated MyBatis

10.1. Add jar

"MyBatis"

Mybatis-3.2.0.jar
Mybatis-spring-1.1.1.jar
Log4j-1.2.17.jar

"Spring"

Spring-aop-3.2.0.release.jar
Spring-beans-3.2.0.release.jar
Spring-context-3.2.0.release.jar
Spring-core-3.2.0.release.jar
Spring-expression-3.2.0.release.jar
Spring-jdbc-3.2.0.release.jar
Spring-test-3.2.4.release.jar
Spring-tx-3.2.0.release.jar
Aopalliance-1.0.jar
Cglib-nodep-2.2.3.jar
Commons-logging-1.1.1.jar

"MySQL driver package"

Mysql-connector-java-5.0.4-bin.jar

10.2. Database Tables

CREATE TABLE s_user (
user_id INT auto_increment PRIMARY KEY,
user_name VARCHAR (),
user_birthday DATE,
user_salary DOUBLE
)

10.3. Entity class: User

public class User {
private int id;
private String name;
Private Date birthday;
private double salary;
Set,get Method
}

10.4.DAO interface: Usermapper (xxxmapper)

Public interface Usermapper {
void Save (user user);
void update (user user);
void Delete (int id);
User FindByID (int id);
List<user> findall ();
}

10.5.SQL mapping File: Usermapper.xml (with interface ignoring case name)

&lt;?xml version= "1.0" encoding= "UTF-8"?&gt; &lt;! DOCTYPE Mapper Public "-//mybatis.org//dtd mapper 3.0//en" "Http://mybatis.org/dtd/mybatis-3-mapper.dtd" &gt; &lt; Mapper namespace= "Com.atguigu.mybatis.test9.UserMapper" &gt; &lt;resultmap type= "User" id= "Userresult" &gt; &lt; Result column= "user_id" property= "id"/&gt; &lt;result column= "user_name" property= "name"/&gt; &lt;result column= "user _birthday "property=" Birthday "/&gt; &lt;result column=" user_salary "property=" salary "/&gt; &lt;/resultMap&gt; &lt;!- -Get the ID--&gt; after inserting data &lt;insert id= "save" keycolumn= "user_id" keyproperty= "id" usegeneratedkeys= "true" &gt; INSERT INTO S_ User (User_name,user_birthday,user_salary) VALUES (#{name},#{birthday},#{salary}) &lt;/insert&gt; &lt;update id= " Update "&gt; Update s_user set user_name = #{name}, User_birthday = #{birthday}, user_salary = #{salary} where user_id = #{ ID} &lt;/update&gt; &lt;delete id= "Delete" &gt; Delete from s_user where user_id = #{id} &lt;/delete&gt; &lt;select id= "fin Dbyid "Resultmap="Userresult &gt; select * from s_user where user_id = #{id} &lt;/select&gt; &lt;select id= "FindAll" resultmap= "Userresult" &
Gt SELECT * FROM S_user &lt;/select&gt; &lt;/mapper&gt;

10.6.spring configuration file: Beans.xml

&lt;?xml version= "1.0" encoding= "UTF-8"?&gt; &lt;beans "xmlns=" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:p= "http://www.springframework.org/schema/p" xmlns:context= "Http://www.springframework.org/schema/context" xmlns:tx= "Http://www.springframework.org/schema/tx" xsi: schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-3.2.xsd Http://www.springframework.org/schema/context Http://www.springframework.org/schema/context /spring-context-3.2.xsd Http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/ Spring-tx-3.2.xsd "&gt; &lt;!--1. Data source: Drivermanagerdatasource--&gt; &lt;bean id= "DataSource" class= " Org.springframework.jdbc.datasource.DriverManagerDataSource "&gt; &lt;property name=" driverclassname "value=" Com.mysql.jdbc.Driver "/&gt; &lt;property name=" url "value=" Jdbc:mysql://localhost:3306/mybatis "/&gt; &lt;property Name= "username" value="Root"/&gt; &lt;property name= "password" value= "root"/&gt; &lt;/bean&gt; &lt;!--2. MyBatis's sqlsession factory: Sqlsessionfactorybean datasource/typealiasespackage--&gt; &lt;bean id= "SqlSessionFactory" class= "Org.mybatis.spring.SqlSessionFactoryBean" &gt; &lt;property name= "dataSource" ref= "DataSource"/&gt; &lt; Property Name= "Typealiasespackage" value= "Com.atuigu.spring_mybatis2.domain"/&gt; &lt;/bean&gt; &lt;!--3. MyBatis automatic Scan load SQL Map file: mapperscannerconfigurer sqlsessionfactory/basepackage--&gt; &lt;bean class= " Org.mybatis.spring.mapper.MapperScannerConfigurer "&gt; &lt;property name=" basepackage "value=" Com.atuigu.spring_ Mybatis2.mapper "/&gt; &lt;property name= sqlsessionfactory" ref= "Sqlsessionfactory"/&gt; &lt;/bean&gt; &lt;!--4. Transaction management: Datasourcetransactionmanager--&gt; &lt;bean id= "Txmanager" class= " Org.springframework.jdbc.datasource.DataSourceTransactionManager "&gt; &lt;property name=" DataSource "ref=" DataSource "/&gt; &lt;/bean&gt; &lt;!--5. Using declarative transactions--&gt; &lt;tx:annotation-Driven transaction-manager= "Txmanager"/&gt; &lt;/beans&gt; 

10.7.mybatis configuration file: Mybatis-config.xml

<?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>
<!--Spring integration MyBatis, this profile can be-->
<!- -Set the external profile-->
<!--set the category name-->
<!--Set the database connection environment-->
<!--mapping file-->
</ Configuration>

10.8. Test

@RunWith (Springjunit4classrunner.class)//Use Springtest Test framework
@ContextConfiguration ("/beans.xml")//Load Configuration
public class Smtest {
@Autowired//inject
private usermapper usermapper;
@Test public
Void Save () {
User user = new user ();
User.setbirthday (New Date ());
User.setname ("Marry");
User.setsalary ();
Usermapper.save (user);
System.out.println (User.getid ());
}
@Test public
Void Update () {
User user = Usermapper.findbyid (2);
User.setsalary ();
Usermapper.update (user);
}
@Test public
Void Delete () {
usermapper.delete (3);
}
@Test public
void FindByID () {
User user = Usermapper.findbyid (1);
SYSTEM.OUT.PRINTLN (user);
}
@Test public
void FindAll () {
list<user> users = Usermapper.findall ();
System.out.println (users);
}

The above is a small set to introduce the MyBatis quick introduction (Concise simple analysis), hope to help everyone, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.