MyBatis basic configuration and simple additions and deletions to check

Source: Internet
Author: User
mybatis Basic configuration and simple additions and deletions to check1.MyBatis is an excellent persistence layer framework that supports custom SQL, stored procedures, and advanced mapping.
2.MyBatis avoids almost all the JDBC code and manually sets the parameters and gets the result set.
3.MyBatis can use simple XML or annotations for configuration and native maps, mapping interfaces and Java POJOs (Plain old Java Objects, normal Java objects) to records in the database.
4. Cut to the chase, there is no detailed analysis of the tags in the configuration, part of the code in the description. The following will be added to the specific meaning of the label, here only to say simple usage. The following inserts a code fragment: A. Configures the MyBatis XML file, named (mybatis-config.xml). As follows:
<?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;configuration> <!--configuration alias if the alias is configured in the SQL map file without writing the corresponding package name ~ can be directly corresponding to the alias--> <typeAliases> <typealia s alias= "user" type= "Com.test.bean.UserInfoBean"/> </typeAliases> <!--Configure Data source information--> <environme NTS default= "Development" > <environment id= "Development" > <transactionmanager type= "JDBC" ></trans actionmanager> <!--pooled pooleddatasourcefactory Use the connection pool data source--> <!--unpooled Unpooledd Atasourcefactory data sources that do not use the connection pool--> <!--Jndi Jndidatasourcefactory Use the JNDI implementation data source--> <!--Typ E= "Pooled" MyBatis creates Pooleddatasource instance type= "unpooled" MyBatis creates Unpooleddatasource instance type= "JNDI" MyBatis will look for DataSource instances from the Jndi service--> <datasource type= "Pooled" > <property name= "Driver" value= "COM.MYSQ" L. jdbc. Driver "/> <property name=" url "value=" jdbc:mysql://127.0.0.1:3306/spring_test?useunicode=true& Characterencoding=utf-8 "/> <!--configuration username--> <property name=" username "value=" root " ;</property> <!--configuration password--> <property name= "password" value= "root" ><
		/property> </dataSource> </environment> </environments> <!--configuration database vendor identification can be omitted--> <databaseidprovider type= "Db_vendor" > <property name= "mysql" value= "MySQL"/> </databaseidprovider > <!--Configuring SQL mappings--> <mappers> <mapper resource= "Userinfomapping.xml"/> < Mapper resource= "Scoremapping.xml"/> <!--If you need to configure the CALSS in an annotated manner.  
   		Because the MyBatis is implemented by means of dynamic proxies--> <mapper class= "Com.test.service.interfaces.ScoreServiceInterface"/> </mappers> </configuration>
B. Creating Userinfobean
Package Com.test.bean;

public class Userinfobean {
	
	private int id;
	
	Private String account  ;
	
	private String name;
	
	private String password;

	public int getId () {return
		ID;
	}

	public void setId (int id) {
		this.id = ID;
	}

	Public String Getaccount () {return account
		;
	}

	public void Setaccount (String account) {
		this.account = account;
	}

	Public String GetName () {return
		name;
	}

	public void SetName (String name) {
		this.name = name;
	}

	Public String GetPassword () {return
		password;
	}

	public void SetPassword (String password) {
		this.password = password;
	}
	

}

C. Create Scorebean
Package Com.test.bean;

public class Scorebean {

	private int id;
	
	private double score;

	public int getId () {return
		ID;
	}

	public void setId (int id) {
		this.id = ID;
	}

	Public double Getscore () {return
		score;
	}

	public void SetScore (double score) {
		this.score = score;
	}
	
	
}

D. Create Userinfoserviceinterface
Package com.test.service.interfaces;

Import Com.test.bean.UserInfoBean;

Public interface Userinfoserviceinterface {

	void Queryuserinfo (Userinfobean userinfobean);

	void Adduserinfo (Userinfobean userinfobean);

	void Updateuserinfo (Userinfobean userinfobean);

	void Deleteuserinfo (Userinfobean userinfobean);

	int Getcountall ();

}

E. Create Scoreserviceinterface. This class is oriented to interface programming, using annotated SQL statements. Do not need to write implementation classes.
Package com.test.service.interfaces;

Import Org.apache.ibatis.annotations.Delete;
Import Org.apache.ibatis.annotations.Insert;
Import Org.apache.ibatis.annotations.Select;
Import org.apache.ibatis.annotations.Update;

Import Com.test.bean.ScoreBean;

Public interface Scoreserviceinterface {
	@Select (value= "Select count (*) from score")
	int getcountall ();
	
	@Select (value= "Select * from score where Id=#{id}")
	Scorebean Getscorebyid (Scorebean scorebean);
	
	@Insert (value= "Insert into  score (score) VALUES (#{score})")
	void Insertscore (Scorebean scorebean);
	
	@Delete (value= "Delete from score where ID =#{id}")
	void Deletescore (Scorebean scorebean);
	
	@Update (value= "Update score set score =#{score} where Id=#{id}")
	void Updatescore (Scorebean scorebean);

	


F. Creating Userinfoserviceimp
Package com.test.service.imp;

Import org.apache.ibatis.session.SqlSession;
Import Com.test.bean.UserInfoBean;
Import Com.test.service.interfaces.UserInfoServiceInterface;

Import Com.test.util.SqlSessionFactoryUtil; public class Userinfoserviceimp implements Userinfoserviceinterface {/* (non-javadoc) * @see com.test.service.imp.u Serinfoserviceinterface#queryuserinfo (Com.test.bean.UserInfoBean) */@Override public void Queryuserinfo (
		Userinfobean Userinfobean) {sqlsession session =sqlsessionfactoryutil.getopensession ();
			try {//Query an object by way of object Userinfobean user = Session.selectone ("Getuserinfobyuser", Userinfobean);
			
			System.out.println ("Through the way of the object account:" +user.getaccount ());
			Query Userinfobean user1 = Session.selectone ("getuserinfodynamic", Userinfobean) by means of SQL dynamic statements;
			
		SYSTEM.OUT.PRINTLN ("Query by means of dynamic statements and objects, account number:" +user1.getaccount ());
		catch (Exception e) {e.printstacktrace ();
		}finally{Session.close (); }/* (non-javadoc) * @see com.Test.service.imp.userinfoserviceinterface#adduserinfo (Com.test.bean.UserInfoBean) */@Override public void Adduserinfo (Userinfobean Userinfobean) {//Build Sqlsession Factory sqlsession session =sqlsessionfactoryutil.getopensession ()
		;
			try {session.insert ("Adduserinfo", Userinfobean);
		Session.commit ();
		catch (Exception e) {e.printstacktrace ();
		}finally{Session.close (); }/* (non-javadoc) * @see Com.test.service.imp.userinfoserviceinterface#updateuserinfo (com.test.bean.UserInfoBea N) */@Override public void Updateuserinfo (Userinfobean userinfobean) {sqlsession session =sqlsessionfactoryutil.ge
		Topensession ();
			try {session.update ("Updateuserinfo", Userinfobean);
		Session.commit ();
		catch (Exception e) {e.printstacktrace ();
		}finally{Session.close (); }/* (non-javadoc) * @see Com.test.service.imp.userinfoserviceinterface#deleteuserinfo (com.test.bean.UserInfoBe AN) */@Override public void Deleteuserinfo (UserinfobeaN Userinfobean) {sqlsession session =sqlsessionfactoryutil.getopensession ();
			try {session.delete ("Deleteuserinfo", Userinfobean);
		Session.commit ();
		catch (Exception e) {e.printstacktrace ();
		}finally{Session.close (); }/* (non-javadoc) * @see com.test.service.imp.userinfoserviceinterface#getcountall () * * * @Override Pub
		LIC int Getcountall () {//Query an object by the way of an object sqlsession session = Sqlsessionfactoryutil.getopensession ();
		int reslut = 0;
			try {reslut=session.selectone ("GetCount");
		SYSTEM.OUT.PRINTLN ("userinfo table Quantity" +reslut);
		catch (Exception e) {e.printstacktrace ();
		finally {session.close ();
	return reslut;
 }

}

G. Creating Sqlsessionfactoryutil. Used to get Sessionfactory
Package com.test.util;
Import java.io.IOException;

Import Java.io.Reader;
Import org.apache.ibatis.io.Resources;
Import Org.apache.ibatis.jdbc.SQL;
Import org.apache.ibatis.session.SqlSession;
Import Org.apache.ibatis.session.SqlSessionFactory;

Import Org.apache.ibatis.session.SqlSessionFactoryBuilder;
	
	public class Sqlsessionfactoryutil {private static sqlsessionfactory sessionfactory =null; /** * Similar to the thread lock, do sync with the * because a lot of create sqlsessionfactory is very wasteful * we only need to take the session can/private static final Class Class_lock =SQ
	
	Lsessionfactoryutil.class;
	
	/** * Empty Parameter construction method * * Private Sqlsessionfactoryutil () {}; /** * Initialize/public static sqlsessionfactory Initsqlsessionfactory () {//MyBatis configuration file String resource = "Myb
			Atis-config.xml "; Reader re = null;
			Character Stream try {re = Resources.getresourceasreader (Resource);
			catch (IOException e) {e.printstacktrace (); }//Sync synchronized (class_lock) {if (null==sessionfactory) {sessionfactory = new SqLsessionfactorybuilder (). build (re);
	} return sessionfactory; /** * Get opensession */public static sqlsession getopensession () {if (null==sessionfactory) {//Initialize sessionf
		Actory initsqlsessionfactory ();
		} System.out.println ("Database type:" +sessionfactory.getconfiguration (). Getdatabaseid ());
		
	return Sessionfactory.opensession ();
 }
	
}

H. Creating Scoremapping.xml If it is annotated, XML does not need to write SQL statements
<?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" > 

	<!--Configure score mapping  If you are using annotations, you may not need to write SQL statements here. -->
	<mapper namespace= "Com.test.service.imp.ScoreBean" >
	
	</mapper>
	

I. Create Userinfomapping.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" > <!-- Place the corresponding mapping--> <mapper namespace= "COM.TEST.SERVICE.IMP.USERINFOSERVICEIMP" > <!--by ID query resulttype= "user"  --> <select id= "Getuserinfobyid" parametertype= "int" resulttype= "user" > select * from UserInfo for previously named aliases where ID =#{id} </select> <!--query--> <select id= "Getuserinfobyuser" parametertype= "user" through objects Resulttype= "User" > select * from userInfo where id = #{id} and Name=#{name} </select> <!--query all quantities --> <select id= "GetCount" resulttype= "int" > SELECT COUNT (*) from UserInfo </select> <!--  
			Like and dynamic statements the way--> <select id= "getuserinfodynamic" parametertype= "user" resulttype= "user" > select * from UserInfo
	<where> <if test= "Id!=null and id!=" "> and Id=#{id} </if>			<if test= "Name!=null" > and Name=#{name} </if> <if test= "Account!=null" > and Accoun T=#{account} </if> </where> </select> <!--update the value returned through dynamic statements is the number of updates--> < Update id= "Updateuserinfo" parametertype= "user" > Update userinfo set <if test= "Name!=null" > Name=#{name } </if> <if test= "Account!=null" > Account=#{account} </if> where Id=#{id} </updat e> <!--delete--> <delete id= "deleteuserinfo" parametertype= "user" > Delete from UserInfo & lt;where> <if test= "id!=null and Id!= '" "> Id=#{id} </if> <if test=" Account!=null and AC Count!= ' "> account=#{account} </if> </where> </delete> <!--adding data by object
		;
				<insert id= "Adduserinfo" parametertype= "user" > INSERT into UserInfo (account, name, password) values (#{account}, #{name}, #{password}) </insert> </mapper> 
J. Create a corresponding test class to J1. Create Scoretest
Package com.test.junit;
Import org.apache.ibatis.session.SqlSession;

Import Org.junit.Test;
Import Com.test.bean.ScoreBean;
Import Com.test.service.interfaces.ScoreServiceInterface;

Import Com.test.util.SqlSessionFactoryUtil; public class Scoretest {@Test public void Test () {sqlsession sqlsession = sqlsessionfactoryutil.getopensession ()
		;
			try {scoreserviceinterface service = Sqlsession.getmapper (Scoreserviceinterface.class);
		
			System.out.println ("Query quantity via interface @select annotation:" + service.getcountall ());
			Scorebean bean = new Scorebean ();
			Query Bean.setid (7) by the way of object;
			Scorebean Scorebean = Service.getscorebyid (bean);
			
			System.out.println ("Querying an object by means of an interface @select annotation" +scorebean.getscore ());
			Insert Data Bean.setscore (212.0);
			
			Service.insertscore (Bean);
			Delete Bean.setid (3);
			Bean.setscore (664);
			
			Service.deletescore (Bean);
			Update Data Bean.setid (7);
			Bean.setscore (12.11);
			
			Service.updatescore (Bean);
		Submit transaction Sqlsession.commit ();	
		catch (Exception e) {e.printstacktrace ();
		}finally{Sqlsession.close ();
 }

	}

}

J2. Create Userinfotest
Package com.test.junit;

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 Org.junit.Test;
Import Com.test.bean.UserInfoBean;
Import COM.TEST.SERVICE.IMP.USERINFOSERVICEIMP;

Import Com.test.service.interfaces.UserInfoServiceInterface;
		public class Userinfotest {@Test the public void Test () {//is queried by ID for String resource = "Mybatis-config.xml";
		sqlsession session = NULL;
			try {Reader re = Resources.getresourceasreader (Resource);
			Sqlsessionfactory sqlsessionfactory = new Sqlsessionfactorybuilder (). build (re);
			Session = Sqlsessionfactory.opensession ();
			SelectOne only returns one piece of data userinfobean user = Session.selectone ("Getuserinfobyid", 10);
		System.out.println (User.getname ());
		catch (Exception e) {e.printstacktrace ();
		finally {session.close (); } userinfoserviceinterface SERvice = new Userinfoserviceimp ();
		Query the Userinfobean userinfobean =new Userinfobean () by the way of object;
		Userinfobean.setid (10);
		Userinfobean.setname ("Test 3");
		
		Service.queryuserinfo (Userinfobean);
		Update Data Userinfobean.setid (10) by object method;
		Userinfobean.setname ("Test 3");
		
		Service.updateuserinfo (Userinfobean);
		
		Delete data//Service.deleteuserinfo (Userinfobean) by object method;
		Inserting Data Userinfobean.setaccount ("1231234") by means of an object;
		Userinfobean.setpassword ("1231234");
		
		Service.adduserinfo (Userinfobean);
		
		
	Query the number of rows Service.getcountall ();
 }

}

Supplemental Source Address: http://download.csdn.net/detail/u013704342/9733555



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.