I. MyBatis INTRODUCTION
1.MyBatis was an open source project for Apache, Ibatis, which was migrated from Apache Software Foundation to Google code in 2010 and renamed MyBatis. Migrated to GitHub in November 2013.
The term ibatis is derived from the combination of "Internet" and "Abatis" and is a Java-based persistence layer framework. The persistence layer framework provided by Ibatis includes SQL maps and Data Access Objects (DAOs).
2. Function structure:
(1) API Interface Layer: provides interface APIs for external use, where developers manipulate databases through these local APIs. Once the interface layer receives the call request, it invokes the data processing layer to complete the specific data processing.
(2) Data processing layer: Responsible for the specific SQL lookup, SQL parsing, SQL execution and execution result mapping processing and so on. Its primary purpose is to complete a database operation at the request of the call.
(3) Base support layer: Responsible for the most basic functional support, including connection management, transaction management, configuration loading and caching processing, these are common things, they are extracted as the most basic components. Provides the most basic support for the data processing layer of the upper layer.
Two. Project examples
Packages that need to be imported: Ojdbc6.jar (Access the database Prerequisites package), Mybatis-3.4.6.jar (MyBatis framework Package), Log4j-1.2.17.jar (Toolkit for console debugging)
Required Files: log4j.properties (debug template)
To configure the total configuration file for MyBatis:
<?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><properties resource= "conf/db.properties" ></properties><!--load Properties file, You can also directly define the property value--><typealiases><!--alias type, which defaults to the class name alias--><package name= "Com.hanqi.model" under the package/><! --<typealias type= "Com.hanqi.model.House" alias= "HHH"/> According to their own alias--></typealiases> <environments default= "Development" ><!--configuration MyBatis operating environment, the general environment has 3, set the default for the development environment--<environment id= "development" ><! --Development environment--<!--configuration transaction manager, there are two ways: 1, JDBC 2, MANAGED (trailer, general Business Server will have this function, such as jboss,weblogic, Tomcat not)-- <transactionmanager type= "JDBC"/><!--configuration Things Manager Type-<!--data Source type parameter has three kinds: unpooled, pooled, jndiunpooled : There is no connection pool, using the most common connection, each call to the database MyBatis will create a new connection, close after use, suitable for small concurrent projects (concurrency: The meaning of user access) pooled: Use the connection pool, create several connections, and then put back the connection pool Jndi: To obtain a database connection using the application server configuration Jndi data source--> <datasource type= "Pooled" ><!--connection pooling-based data sources, using connection pooling to avoid duplication of connections to the database-<property name= "Driver" value= "${jdb C.classname} "/><!--Configure 4 properties of the connected database--<property name=" url "value=" ${jdbc.url} "/> <property Name= "username" value= "${jdbc.username}"/> <property name= "password" value= "${jdbc.password}"/> </ datasource> </environment> </environments> <mappers><!--Configure map file paths, load map files--<mapper Resource= "Mapper/*.xml"/> <!--if you use <package> to scan a mapping file in a package, you must use the Sqlsession.getmapper (interface. Class) To define the method and the XML map file name must be the same as the name of the interface because the <package> scan is not an XML mapping file, but rather a scanned. java file--</mappers></configuration >
Connection Database Properties File:
Jdbc.username=test0315jdbc.password=123456jdbc.url=jdbc:oracle:thin: @localhost: 1521:xejdbc.classname= Oracle.jdbc.OracleDriver
Build sqlsession:
Package Util;import Java.io.ioexception;import Java.io.inputstream;import org.apache.ibatis.io.resources;import Org.apache.ibatis.session.sqlsession;import Org.apache.ibatis.session.sqlsessionfactory;import org.apache.ibatis.session.sqlsessionfactorybuilder;/* * 1, building sqlsessionfactoryinputstream in = Resources.getresourceasstream (the path under the SRC where the total configuration file is located); Sqlsessionfactory SSF = new Sqlsessionfactorybuilder (). Build (in), 2, build sqlsession (note sqlsession cannot be returned as a class member variable) sqlsession ss = Ssf.opensession (); 3, run directly A: Run the SQL statement in the map file directly ss.select...ss.insert...ss.update...ss.delete...b: Use interface map configuration file Ss.getmapper (interface class name. Class); method to invoke interface * */public class Mybatisutil {public static sqlsession getsqlsession () { Return Getsqlsessionfactory (). Opensession ();//build sqlsession instance}public static void Main (string[] args) { System.out.println (Getsqlsession ());} public static Sqlsessionfactory Getsqlsessionfactory () {String resource = "conf/mybatis-config.xml";// Total profile path name InputStream InputStream = null;try {InputStream = resources.geTresourceasstream (Resource);//read config file using input stream} catch (IOException e) {e.printstacktrace ();} Build an instance of sqlsessionfactory sqlsessionfactory sqlsessionfactory = new Sqlsessionfactorybuilder (). Build (InputStream); (InputStream! = null) {try {inputstream.close ();} catch (IOException e) {e.printstacktrace ()}} return sqlsessionfactory;}
Physical model layer:
Package Com.hanqi.model;import java.util.date;import java.util.list;//@Alias (value= "CCC")//can also be aliased by annotations on entity classes, Precedence over other configuration public class Appuser {private Integer ids;private string uname;private string Pword;private string Realname;privat E Date createtime;private integer mark;private integer sex;private list<accounts> accounts;public integer getIds () {return IDs;} public void Setids (Integer ids) {this.ids = IDs;} The following ellipsis
Package Com.hanqi.model;import java.util.date;import java.util.list;//@Alias (value= "CCC")//can also be aliased by annotations on entity classes, Precedence over other configuration public class Appuser {private Integer ids;private string uname;private string Pword;private string Realname;privat E Date createtime;private integer mark;private integer sex;private list<accounts> accounts;public integer getIds () {return IDs;} public void Setids (Integer ids) {this.ids = IDs;} The following ellipsis
Interface layer:
Package Com.hanqi.dao;import Java.util.list;import Com.hanqi.model.accounts;public interface Accountsdao {int Insertaccounts (Accounts Accounts); List<accounts> selectaccounts (); int Deleteaccountsbyuserid (Integer IDs);}
Package Com.hanqi.dao;import java.util.list;import Java.util.map;import Com.hanqi.model.appuser;public interface Appuserdao {int Insertappuser (appuser appuser); int updateappuserbyuname (Appuser appuser); list<appuser> selectappuserbysex (integer sex); int deleteappuserbyids (integer IDs); List<appuser> selectappuserbyparams (map map);}
Data access mapping File 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.hanqi.dao.AppuserDao" ><!--Configure the Map file/interface full path name--><sql id= "Appuser" ><!--for each entity class Configure SQL statements-->ids,uname,pword,realname,createtime,mark,sex</sql><!--dynamically add data operations, pass parameters, #{} is written in the map collection of the key or the entity class member variable name--><!--need to make a data type declaration, otherwise if NULL can not be placed in the database, error--><insert id= "Insertappuser" Parametertype= "Appuser" ><!--called ID/Method name, the result type is entity class--><!--Selectkey is used to obtain the primary key of the added data, Oracle does not support self-increment, with before, Need to get primary key--><selectkey keyproperty= "IDs" order= "before" resulttype= "Integer" keycolumn= "IDs" through the GetIDs method > Select Sq_test.nextval IDs from dual<!--dual refers to pseudo-columns--></selectkey>insert into Appuser (<include refid= " Appuser "></include>" values (#{ids},#{uname,jdbctype = Varchar},#{pword,jdbctype = Varchar},#{realname, Jdbctype = Varchar},sysdate,1,#{sex,jdbctype = DECIMAL}) </insert><!--modify by condition--><update id= "updateappuserbyuname" parametertype= "Appuser" ><!--parameter type is entity class-- Update Appuser<set>pword = #{pword},</set> <where>and uname = #{uname}</where> </update> <!--a one-to-many joint query through gender conditions--><resultmap type= "Appuser" id= "appuserlist" ><id property= "IDs" column= "IDs"/ ><collection property= "Accounts" column= "IDS" select= "Com.hanqi.dao.AccountsDao.selectAccountsByUserId" > </collection></resultmap><select id= "Selectappuserbysex" resultmap= "AppuserList" parameterType= " The Integer ">select * from appuser where sex = #{sex}</select><!--through the ID query result--><!-- MyBatis automatically matches the column name of the query result to the member variable name of the entity class, and if you call the Set method, put it in--><select id= "Selectappuserbyids" parametertype= "Integer" Resulttype= "Appuser" >select * from appuser where ids = #{ids}</select><!--are tombstoned by ID criteria--><update id= "Deleteappuserbyids" parametertype= "Integer" >update appuser set mark = 0 where ids = #{ids}</update><!--Query by Parameters--><select id= "Selectappuserbyparams" parametertype= "Map" resulttype= "Appuser" >select <include refid= "Appuser" ></include> from appuser<where><if test= "sex! = null" >and Sex=#{sex} </if><if test= "Plist! = null" >and IDs in<foreach collection= "plist" item= "IDs" open= "(" close= ")" Separator= "," >#{ids}</foreach></if></where></select></mapper>
<?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.hanqi.dao.AccountsDao" ><insert id= "insertaccounts" parametertype= "Accounts" >insert Into Accounts<trim prefix= "(" suffix= ")" suffixoverrides= "," ><!--trim usage-->ids,<if test= "Acco! = null" >acco,</if><if test= "Passwords! = null" >passwords,</if><if test= "Tel! = null" >tel,</if ><if test= "Email! = NULL" >email,</if><if test= "Ptail! = null" >ptail,</if><if test= " UserID! = null ">userid,</if>regtime,<if test=" Note! = NULL ">note,</if>mark,</trim>< Trim prefix= "VALUES (" suffix= ")" suffixoverrides= "," >sq_test.nextval,<if test= "Acco! = null" >#{acco},</ If><if test= "Passwords! = null" >#{passwords},</if><if test= "Tel! = null" >#{tel},</if>< If test= "Email! = NULL" >#{emAil},</if><if test= "Ptail! = null" >#{ptail},</if><if test= "UserID! = null" >#{userid},</if >sysdate,<if test= "Note! = null" >#{note},</if>1,</trim></insert><!--by ID query-- <select id= "Selectaccountsbyuserid" parametertype= "Integer" resulttype= "Accounts" >select * from Accounts where UserID = #{userid}</select><!--One-to-one query the first method--><!--<resultmap type= "Accounts" id= "Accountslist" > The result set is defined as the entity class <id column= "IDs" property= "IDs"/>id is used to record the primary key, column is the value of the column name and assigned to the member variable of the entity class; <result column= "ACCO" Property= "Acco"/><result column= "passwords" property= "passwords"/><result column= "Tel" property= "Tel"/ ><result column= "Email" property= "email"/><result column= "Ptail" property= "Ptail"/><result column = "Regtime" property= "Regtime"/><result column= "note" property= "note"/><result column= "UNAME" property= " Appuser.uname "/><result column=" Pword "property=" Appuser.pword "/></resultmap> <select id= "selectaccounts" resultmap= "Accountslist" >id refers to the method in the interface, RESULTMAP refers to a defined set of select * FROM Accoun TS Ac,appuser ap where Ac.userid = Ap.ids </select> <!--The second method, object Cascade--><resultmap type= "Accounts" Id= "Accountslist" ><association property= "Appuser" column= "USERID" select= " Com.hanqi.dao.AppuserDao.selectAppuserByIds "></association></resultMap><!--one-to-one joint query-->< Select Id= "selectaccounts" resultmap= "Accountslist" >select * from accounts</select><!--removed by conditional logic-- <update id= "Deleteaccountsbyuserid" parametertype= "Integer" >update accounts set mark = 0 where UserID = #{userid}&l T;/update></mapper>
Test class:
Package Test;import Java.util.arraylist;import Java.util.hashmap;import java.util.list;import java.util.Map;import Org.apache.ibatis.session.sqlsession;import Org.junit.jupiter.api.aftereach;import Org.junit.jupiter.api.beforeeach;import Org.junit.jupiter.api.test;import Com.hanqi.dao.accountsdao;import Com.hanqi.dao.appuserdao;import com.hanqi.model.accounts;import com.hanqi.model.appuser;import util. Mybatisutil;public class Junittest {private sqlsession sqlsession;private Appuserdao appuserdao;private AccountsDao Accountsdao; @BeforeEachvoid setUp () throws Exception {sqlsession = Mybatisutil.getsqlsession (); Appuserdao = Sqlsession.getmapper (appuserdao.class); Accountsdao = Sqlsession.getmapper (Accountsdao.class);} @AfterEachvoid TearDown () throws Exception {Sqlsession.commit (); Sqlsession.close ();} @Testvoid Test () {//Add operation Appuser appuser = new Appuser () appuser.setuname ("Xiaoming 1"); Appuser.setpword ("112345");// Appuser.setrealname ("Harry"); Appuser.setsex (2); int r = Appuserdao.insertappuser (appuser); System.out.println (Appuser.getids ()); System.out.println (R);//multi-parameter query operation map MAP1 = new hashmap<> (); List<integer> List1 = new arraylist<> (); List1.add (361); List1.add (442); List1.add (495); Map1.put ("Sex", 2) ; Map1.put ("plist", List1); list<appuser> list = Appuserdao.selectappuserbyparams (MAP1);p(list);} private void P (list<appuser> List) {for (Appuser a:list) {System.out.println (a);}} void Test1 () {//modify operation Appuser Appuser = new Appuser (); Appuser.setpword ("hq1111"); Appuser.setuname ("admin"); int a = Appuserdao.updateappuserbyuname (Appuser); System.out.println (a);//tombstone Operation Appuserdao.deleteappuserbyids (361); Accountsdao.deleteaccountsbyuserid (61);}}
Special Symbolic Expressions:
< < less sign
> > Greater than sign
& & and
' ' Single quotation mark
" "Double quotation marks
Example: SELECT * from emp where Sal < #{sal}
<! [cdata[]]> is referred to the next level, namely the database.
Example: <! [Cdata[select * from EMP where Sal < #{sal}]]>
JAVA Framework-mybatis