I. A brief introduction:
MyBatis, an open source project for Apache, Ibatis the project was migrated from Apache Software Foundation to Google code in 2010 and renamed MyBatis.
MyBatis is a Java-based persistence layer framework.
Two. Additions and deletions:
1. Code structure diagram:
2. User entity class:
/** * User entity class */public class User {private string id;private string uname;//Note: The field name is inconsistent with the database field private string address; @Ov Erridepublic String toString () {return ' {id: ' + ID + ', uname: ' + uname + ', Address: ' + address + '} ';}
Omit getter and Setter methods
3. Entity mapping File: User.xml
<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE mapperpublic "-//mybatis.org//dtd Mapper 3.0//en" "Http://mybatis.org/dtd/mybatis-3-mapper.dtd" >< Mapper namespace= "Com.zdp.domain.User" ><!--database fields corresponding to entity fields--><resultmap type= "User" id= "UserBean" > <id column= "id" property= "id"/><result column= "username" property= "uname"/><result column= "Address" property= "Address"/></resultmap><!--: Query all user--><select id= "selectallusers" resultmap= " UserBean ">select ID, username, address from user</select><!--: query user by ID, return value userBean--><!--ID: Unique identifier of the current SQL statement, ParameterType: Parameter type, Resulttype: return value type--><select id= "Selectuserbyid" parametertype= "string" resultmap= "UserBean" >select * from user where id = #{userid}</select><!--: Query user by ID, return value is HashMap-->&L T;select id= "Selectuserbyidformap" parametertype= "string" resulttype= "HashMap" >select ID, username, address from User where id = #{userid}</select><!--add: Insert User, number of Userbean (call getter method to get the number)--><insert id= "Insertuser" parametertype= "User" >insert into user (ID, username, address) VALUES (#{id}, #{uname}, #{address});</insert><!--add: Insert User, the number of references is HashMap ( Call Usermap.get (key) to get the number of references)--><insert id= "Insertuserformap" parametertype= "HashMap" >insert into user (ID, Username, address) VALUES (#{id}, #{uname}, #{address});</insert><!--Delete: Deletes the user by ID, the number of references is UserID-->< Delete id= "Deleteuserbyid" parametertype= "string" >delete from user where id = #{userid}</delete><!--changed: Update user by ID, number of Userbean (call getter method to get the reference)--><update id= "Updateuserbyid" parametertype= "user" >update user Set username = #{uname}, address = #{address} where id = #{id}</update><!--change: Update user by ID, reference map (call Usermap.get (k EY)--><update id= "Updateuserbyidformap" parametertype= "HashMap" >update user set username = #{uname}, Address = #{address} where id = #{id}</update><!--: Dynamic sql: Using the wheRe 1=1 "--><select id=" SelectUserByCondition1 "parametertype=" User "resultmap=" UserBean ">select ID, username , address from user where 1=1<if test= "id! = NULL" >and id = #{id}</if><!--uname refers to the entity's properties--><if test= "Uname! = NULL" >and username = #{uname}</if><if test= "Address! = NULL" >and address = #{address}</if> </select><!--: Dynamic sql: Using the Where tab--><select id= "SelectUserByCondition2" parametertype= "User" resultmap= "UserBean" >select ID, username, address from user<where><if test= "id! = NULL" > id = #{id}</ if><!--uname refers to the entity's properties--><if test= "uname! = NULL" >and username = #{uname}</if><if test= "Address ! = NULL ">and address = #{address}</if></where></select></mapper>
4. Global configuration file: Sqlmapconfig.xml
<?
XML version= "1.0" encoding= "UTF-8"?
><! DOCTYPE configurationpublic "-//mybatis.org//dtd Config 3.0//en" "Http://mybatis.org/dtd/mybatis-3-config.dtd" > <configuration><typealiases><typealias type= "Com.zdp.domain.User" alias= "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://localhost/test "/><property name=" Username "value=" root "/><property name=" password "value=" root "/></datasource></environment> </environments><mappers>< location of the!--mapping file--><mapper resource= "Com/zdp/domain/user.xml"/></ Mappers></configuration>
Typealiases: Specifies an alias for the Java type and can replace the fully qualified name of the Java class with an alias in the XML file.
5. sql file:
CREATE DATABASE test; Use test; CREATE TABLE USER ( ID varchar (PRIMARY) KEY, username varchar (+), address varchar (+) ) INSERT into USER (ID, username, address) VALUES ("001", "Zhangsan", "Wuhan"); INSERT into USER (ID, username, address) VALUES ("002", "Lisi", "Shanghai");
6. log4j
Log4j.rootlogger=debug, consolelog4j.appender.console= org.apache.log4j.consoleappenderlog4j.appender.console.layout= org.apache.log4j.patternlayoutlog4j.appender.console.layout.conversionpattern=%d [%t]%-5p [%c]-%m% nlog4j.logger.java.sql.resultset=infolog4j.logger.org.apache=infolog4j.logger.java.sql.connection= Debuglog4j.logger.java.sql.statement=debuglog4j.logger.java.sql.preparedstatement=debug
7. Test file:
/** * Test Mybatis-user additions and deletions change */public class Usertest {private sqlsessionfactory ssf; @Beforepublic void Initsf () throws Exce ption {String resource = "Sqlmapconfig.xml"; InputStream InputStream = Resources.getresourceasstream (Resource); SSF = new Sqlsessionfactorybuilder (). Build (InputStream);} Query all user@testpublic void Testselectallusers () throws Exception {sqlsession session = Ssf.opensession (); list<user> users = session.selectlist ("Com.zdp.domain.User.selectAllUsers"); for (User user:users) { SYSTEM.OUT.PRINTLN (user);}} Query user based on ID, return value userbean@testpublic void Testselectuserbyid () throws Exception {sqlsession session = Ssf.opensession ( ); User user = Session.selectone ("Com.zdp.domain.User.selectUserById", "001"); SYSTEM.OUT.PRINTLN (user);} Query user based on ID, return value hashmap@testpublic void Testselectuserbyidformap () throws Exception {sqlsession session = Ssf.opensession (); map<string, object> UserMap = Session.selectone ("Com.zdp.domain.User.selectUserByIdForMap", "001"); System.out.println (USERMAP);} Insert user, number of userbean@testpublic void Testinsertuser () throws Exception {sqlsession session = Ssf.opensession ();//Build entity U Ser user = new User (), User.setid ("003"), User.setuname ("Wangwu"); User.setaddress ("Beijing"); int i = Session.insert (" Com.zdp.domain.User.insertUser ", User);//COMMIT Transaction Session.commit ();} Insert user, number of hashmap@testpublic void Testinsertuserformap () throws Exception {sqlsession session = Ssf.opensession (); map<string, object> usermap = new hashmap<string, object> (), Usermap.put ("id", "004"), Usermap.put ("uname", "Zhaoliu"); Usermap.put ("Address", "Tianjin"); int i = Session.insert ("Com.zdp.domain.User.insertUserForMap", UserMap ); Session.commit ();} Delete User by ID, number of userid@testpublic void Testdeleteuserbyid () throws Exception {sqlsession session = Ssf.opensession (); int i = session.delete ("Com.zdp.domain.User.deleteUserById", "004"); Session.commit ();} Update user by ID, number of userbean@testpublic void Testupdateuserbyid () throws Exception {sqlsession session = Ssf.openSession (); User user = new user (), User.setid ("001"), User.setuname ("zhangsanf"); User.setaddress ("Wuhan"); int i = Session.update (" Com.zdp.domain.User.updateUserById ", User); Session.commit ();} Update user by ID, number of hashmap@testpublic void Testupdateuserbyidformap () throws Exception {sqlsession session = Ssf.opensession (); map<string, object> usermap = new hashmap<string, object> (), Usermap.put ("id", "001"), Usermap.put ("uname", "Zhangsan"); Usermap.put ("Address", "Beijing"); int i = Session.update ("Com.zdp.domain.User.updateUserByIdForMap", USERMAP); Session.commit ();} Dynamic condition query: @Testpublic void Testselectuserbycondition () throws Exception {sqlsession session = Ssf.opensession (); User user = new user (); User.setuname ("Lisi"); list<user> users = session.selectlist ("Com.zdp.domain.User.selectUserByCondition1", User);//List<user> Users = Session.selectlist ("Com.zdp.domain.User.selectUserByCondition2", user); for (user u:users) { SYSTEM.OUT.PRINTLN (U);}}
Sqlsessionfactory is a factory class that creates sqlsession, and with sqlsession instances, developers can do business logic directly, and no need to write JDBC-related template code over and over again.
Copyright notice: This article Bo Master original articles, blogs, without consent may not be reproduced.
MyBatis in Crud