Configuration.xml, mybatis master configuration file
<?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" > & lt;! --Note: Each label must be written sequentially and will prompt for error:--> <configuration> <!--property Configuration--<properties resource= "Jdbc.properties"/ > <!--set cache and lazy load, and so on. Important runtime behavior--<settings> <!--set the time-out time, which determines how long the driver waits for a database response--<setting N Ame= "Defaultstatementtimeout" value= "25000"/> </settings> <!--aliases--<typeAliases> <typeal
IAS alias= "User" type= "Com.mybatis.model.User"/> </typeAliases> <environments default= "Development" > <!--environment element Body contains environment configuration for transaction management and connection pooling--<environment id= "Development" > <transactionmanager type= "JD BC "/> <datasource type=" Pooled "> <property name=" Driver "value=" ${driver} "/> <property name = "url" value= "${url}"/> <property name= "username" value= "${username}"/> <propertY name= "password" value= "${password}"/> </dataSource> </environment> </environments> <!- -ORM Mapping File--<mappers> <mapper resource= "Com/mybatis/model/usersqlmap.xml"/> </mappers> </co Nfiguration>
Jdbc.properties
Driver=com.mysql.jdbc.driver
url=jdbc:mysql://localhost:3306/test?useunicode=true&characterencoding= UTF-8
username=root
password=123456
Log4j.properties
Log4j.rootlogger=debug, stdout, R
log4j.appender.stdout=org.apache.log4j.consoleappender
Log4j.appender.stdout.layout=org.apache.log4j.patternlayout
Log4j.appender.stdout.layout.ConversionPattern =%5p-%m%n
log4j.appender.r=org.apache.log4j.rollingfileappender
log4j.appender.r.file=firestorm.log
log4j.appender.r.maxfilesize=100kb
log4j.appender.r.maxbackupindex=1
log4j.appender.r.layout= Org.apache.log4j.PatternLayout
log4j.appender.r.layout.conversionpattern=%p%t%c-%m%n
Log4j.logger.com.codefutures=debug
User. java
Package Com.mybatis.model;
Import java.io.Serializable;
@SuppressWarnings ("Serial") Public
class User implements Serializable {
private int id;
Private String userName;
private String password;
Public User () {
} 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 GetPassword () {
return password;
}
public void SetPassword (String password) {
this.password = password;
}
}
Usersqlmap.xml
<?xml version= "1.0" encoding= "UTF-8"?> <! DOCTYPE Mapper Public "-//ibatis.apache.org//dtd mapper 3.0//en" "HTTP://IBATIS.APACHE.ORG/DTD/IBATIS-3-MAPPER.D TD "> <!--namespace Mapper file that recognizes the specified XML when Java code is called--<mapper namespace=" Com.mybatis.model.User "> &L t;! --Configure ORM Mapping--<resultmap type= "User" id= "User_orm" > <id property= "id" column= "id"/> <result proper Ty= "UserName" column= "UserName"/> <result property= "password" column= "password"/> </resultMap> <!- -Used to define reusable SQL code Snippets--<sql id= "Demo_sql" > Username,password </sql> <insert id= "Inser_user" pa Rametertype= "User" > <!--include references to reusable SQL code Snippets--INSERT into User (<include refid= "Demo_sql"/>) VALUES ( #{username},#{password}) </insert> <update id= "Update_user" parametertype= "user" > Update user SET Userna Me=#{username}, Password=#{password} where Id=#{id} </update> <update id= "deletE_user "parametertype=" int "> DELETE from User WHERE Id=#{id} </update> <select id=" Selectall_user "u Secache= "false" flushcache= "true" resultmap= "User_orm" > select * from User </select> <!--using map Descendants of multiple parameters--<select id= "Selectlist_user" usecache= "false" flushcache= "true" parametertype= "map" resultmap= "User_ ORM "> select * from USER LIMIT #{pagenow},#{pagesize} </select> <select id=" Selectbyid_user "p arametertype= "int" resulttype= "user" > select * from User WHERE id= #{id} </select> <select id= " Selectcount_user "resulttype=" int "> SELECT COUNT (*) from user </select> <select id=" Selectbyn Ame_user "parametertype=" String "resulttype=" User "> select * from User WHERE username= #{username} </select&
Gt
<!--Blur Myibatis 3.2.0--> <select id= "Selectuserbyname" parametertype= "String" resultmap= "User_orm" > SELECT * from USER WHERE userName like "%" #{username} "%" </select> </mapper>
Sessionfactoryutil.java MyBatis Tool class for creating sqlsessionfactory
Package com.mybatis.sessionfactory;
Import java.io.IOException;
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;
public class Sessionfactoryutil {private static final String RESOURCE = "Configuration.xml";
private static sqlsessionfactory sqlsessionfactory = null;
private static threadlocal<sqlsession> ThreadLocal = new threadlocal<sqlsession> ();
static {reader reader = null;
try {reader = Resources.getresourceasreader (RESOURCE);
} catch (IOException e) {throw new RuntimeException ("Get Resource error:" +resource, E);
} sqlsessionfactory = new Sqlsessionfactorybuilder (). build (reader); }/** * Function: Get sqlsessionfactory */public static sqlsessionfactory Getsqlsessionfactory () {Retu
RN Sqlsessionfactory; }/** * Function: Re-create Sqlsessionfactory
*/public static void Rebuildsqlsessionfactory () {reader reader = null;
try {reader = Resources.getresourceasreader (RESOURCE);
} catch (IOException e) {throw new RuntimeException ("Get Resource error:" +resource, E);
} sqlsessionfactory = new Sqlsessionfactorybuilder (). build (reader); }/** * Function: Gets sqlsession */public static sqlsession getsession () {sqlsession session = Threadlocal.get (
);
if (session!=null) {if (sqlsessionfactory = = null) {getsqlsessionfactory (); }//If Sqlsessionfactory is not empty then get sqlsession, otherwise null session = (SQLSESSIONFACTORY!=NULL) is returned?
Sqlsessionfactory.opensession (): null;
} return session;
}/** * Function: Close sqlsession */public static void CloseSession () {sqlsession session = Threadlocal.get ();
Threadlocal.set (NULL);
if (session!=null) {session.close (); }
}
}
Userdao interface
Package Com.mybatis.dao;
Import java.util.List;
Import Com.mybatis.model.User;
Public interface Userdao {public
User load (int id);
public void Add (user user);
public void update (user user);
public void Delete (int id);
Public User findbyname (String userName);
Public list<user> Queryalluser ();
Public list<user> List (int pagenow,int pageSize);
public int getallcount ();
}
Userdaoimpl
Package com.mybatis.dao.implment;
Import Java.util.HashMap;
Import java.util.List;
Import Java.util.Map;
Import org.apache.ibatis.session.SqlSession;
Import Com.mybatis.dao.UserDao;
Import Com.mybatis.model.User;
Import Com.mybatis.sessionfactory.SessionFactoryUtil; public class Userdaoimpl implements Userdao {public User load (int id) {sqlsession session = SESSIONFACTORYUTIL.GETSQ
Lsessionfactory (). Opensession ();
User user = (user) Session.selectone ("Com.mybatis.model.User.selectById_user", id);
Session.close ();
return user;
public void Add (user user) {sqlsession session = Sessionfactoryutil.getsqlsessionfactory (). Opensession ();
Session.insert ("Com.mybatis.model.User.inser_user", User);
Session.commit ();
Session.close ();
public void update (user user) {sqlsession session = Sessionfactoryutil.getsqlsessionfactory (). Opensession ();
Session.update ("Com.mybatis.model.User.update_user", User);
Session.commit ();
Session.close (); } public void DelETE (int id) {sqlsession session = Sessionfactoryutil.getsqlsessionfactory (). Opensession ();
Session.delete ("Com.mybatis.model.User.delete_user", id);
Session.close (); Public User findbyname (String userName) {sqlsession session = Sessionfactoryutil.getsqlsessionfactory (). opensession
();
User user = (user) Session.selectone ("Com.mybatis.model.User.selectByName_user", userName);
Session.close ();
return user; } @SuppressWarnings ("Unchecked") public list<user> Queryalluser () {sqlsession session = Sessionfactoryutil.ge
Tsqlsessionfactory (). Opensession ();
list<user> list = session.selectlist ("Com.mybatis.model.User.selectAll_user");
Session.close ();
return list; } @SuppressWarnings ("Unchecked") public list<user> List (int pagenow, int pageSize) {sqlsession session = Sess
Ionfactoryutil.getsqlsessionfactory (). Opensession ();
map<string,object> params = new hashmap<string,object> ();
Params.put ("Pagenow", Pagenow); Params.puT ("PageSize", pageSize);
list<user> list = session.selectlist ("Com.mybatis.model.User.selectList_user", params);
Session.close ();
return list;
} public int Getallcount () {sqlsession session =sessionfactoryutil.getsqlsessionfactory (). Opensession ();
int count = (Integer) session.selectone ("Com.mybatis.model.User.selectCount_user");
Session.close ();
return count; }
}
Test class:
Package com.mybatis.dao.implment;
Import java.util.List;
Import Org.junit.Test;
Import Com.mybatis.dao.UserDao;
Import Com.mybatis.model.User;
public class Userdaotest {private Userdao Userdao = new Userdaoimpl ();
@Test public void TestLoad () {User u = userdao.load (1);
if (u!=null) {System.out.println ("UserId:" +u.getid () + "UserName:" +u.getusername () + "Password:" +u.getpassword ()); } else{System.out.println ("ID does not exist:
");
}} @Test public void Testadd () {User user = new User ();
User.setusername ("Admin5");
User.setpassword ("123456");
Userdao.add (user);
} @Test public void Testupdate () {User user = new User ();
User.setid (2);
User.setusername ("manager");
User.setpassword ("123456");
Userdao.update (user);
} @Test public void Testqueryalluser () {list<user> List = Userdao.queryalluser (); if (List!=null&list.size () >0) {for (User u:list) {System.out.println ("UserId:" +u.getid () + "UserName:" +u.getus Ername () + "PasswoRD: "+u.getpassword ());
}}} @Test public void Testfindbyname () {User u = userdao.findbyname ("admin");
if (u!=null) {System.out.println ("UserId:" +u.getid () + "UserName:" +u.getusername () + "Password:" +u.getpassword ()); } else{System.out.println ("User name does not exist:
");
}} @Test public void Testlist () {list<user> List = userdao.list (1, 4); if (List!=null&list.size () >0) {for (User u:list) {System.out.println ("UserId:" +u.getid () + "UserName:" +u.getus
Ername () + "Password:" +u.getpassword ());
}}} @Test public void Testgetallcount () {System.out.println ("All Count:" +userdao.getallcount ());
} @Test public void Testdelete () {userdao.delete (3); }
}