MyBatis Small Test crud

Source: Internet
Author: User

First Use MyBatis, Contacts table to do a check and delete.

Contacts Table Structure:

+---------+------------------+
| Field | Type |
+---------+------------------+
| ID | int (a) unsigned |
| name | varchar (45) |
| Address | varchar (45) |
| Gender | char (1) |
| Dob | datetime |
| email | varchar (45) |
| Mobile | varchar (15) |
| Phone | varchar (15) |
+---------+------------------+

Eclipse Engineering Structure:


The official document directly copy the MyBatis main configuration file, slightly modified, save as configuration.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> <properties resource= "db.properties" > </properties> <typeAliases> <typeal IAS type= "com.mybatistest.bean.Contact" alias= "Contact"/> </typeAliases> <environments default= Development "> <environment id=" Development "> <transactionmanager type=" JDBC "/> <datasource type
				= "Pooled" > <property name= "Driver" value= "${driver}"/> <property "url" name= "value=}" ${url <property name= "username" value= "${username}"/> <property name= "password" value= "${password}"/> </ datasource> </environment> </environments> <mappers> <mapper resource= "Com/mybatistest/bea N/contactmapper.xml "/> </mappers> </configuration> 
Generate the Entity class Contact.java and create the corresponding Contactmapper.xml file as follows:

<?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 "> <mapper namespace=" com.mybatistest.mapper.ContactMapper "> <select id=" selectlist "Resultty Pe= "Contacts" > select * from Contacts </select> <select id= "Selectbyname" Parametert Ype= "String" resulttype= "Contacts" > select * from contacts where name like Concat ('% ', #{name}, '% ') </select&
    Gt <select id= "findcontact" parametertype= "int" resulttype= "Contacts" > select * from Contacts where Id=#{id} &L t;/select> <update id= "updatecontact" parametertype= "Contact" > Update contacts Set Name=#{name},a Ddress=#{address},gender=#{gender}, Dob=#{dob},email=#{email},mobile=#{mobile},phone=#{phone} where Id=#{id} < 
   /update> <insert id= "insertcontact" parametertype= "Contact" 	Usegeneratedkeys= "true" keyproperty= "id" > INSERT into Contacts (Name,address,gender,dob,email,mobile,phone) VALUES (#{name},#{address},#{gender},#{dob},#{email},#{mobile},#{phone}) </insert> <delete id= "Del Etecontact "parametertype=" int "> Delete from Contacts where Id=#{id} </delete> </mapper>
The first time to write like query is used as '%#{name}% ', the results are not found, online after, someone gave the suggestion is contact ('% ', #{name}, '% '), so take it.

Also, a contactmapper interface is generated, as follows:

Public interface Contactmapper {
	list<contact> selectlist ();
	List<contact> selectbyname (String name);
	Contact findcontact (int id);
	int updatecontact (contact contacts);
	int insertcontact (contact contacts);
	int deletecontact (int id);
}

The following is the implementation of the CRUD operation

public class Contactdaoimpl implements Contactdao {private sqlsession session;//private Transaction Transaction;//
		Private Contactmapper Getcontactmapper () {session = Dbutil.getsqlsession ();
		Get mapper Contactmapper mapper = Session.getmapper (Contactmapper.class);
	return mapper;
		private void CloseSession () {if (session!=null) {session.close ();
		}//query All public list<contact> query () {Contactmapper mapper = Getcontactmapper ();
		list<contact> list = Mapper.selectlist ();
	return list;
		//query by name Public list<contact> query (String name) {Contactmapper mapper = Getcontactmapper ();
		list<contact> list = mapper.selectbyname (name);
	return list;
		//find one by ID public contacts find (int id) {Contactmapper mapper = Getcontactmapper ();
	return mapper.findcontact (ID);
		//update Contacts public int update (contacts contact) {Contactmapper mapper = Getcontactmapper (); Transaction = Dbutil.gettransaction (session);
		Transactio begin int rows = mapper.updatecontact (contact);
		try {transaction.commit ();//commit} catch (SQLException e) {e.printstacktrace ();
		}finally{closesession (); } return rows; return effected rows}//insert contacts to db public int insert (contacts contact) {Contactmapper mapper = Getconta
		Ctmapper ();
		Transaction = Dbutil.gettransaction (session);
		int rows = mapper.insertcontact (contact);
		try {transaction.commit ();
		catch (SQLException e) {e.printstacktrace ();
		}finally{closesession ();
	} return rows;
		//delete Contact by id public int delete (int id) {Contactmapper mapper = Getcontactmapper ();
		Transaction = Dbutil.gettransaction (session);
		int rows = mapper.deletecontact (ID);
		try {transaction.commit ();
		catch (SQLException e) {e.printstacktrace ();
		}finally{closesession ();
	} return rows; }
}
After refactoring, generate interface Contactdao.

Here is the tool class Dbutil.java

public class Dbutil {
	private static sqlsessionfactory sessfactory = null;
	private static transactionfactory transfactory = null;
	static{
		Reader reader = null;
		try {
			reader = Resources.getresourceasreader ("Configuration.xml");
		} catch (IOException e) {
			E.printstacktrace ();
		}
		Sessfactory = new Sqlsessionfactorybuilder (). build (reader);
		Transfactory = new Jdbctransactionfactory ();
	}
	
	
	public static Transaction Gettransaction (Sqlsession sessions) {return
		transfactory.newtransaction ( Session.getconnection ());
	}
	
	public static sqlsession Getsqlsession () {return
		sessfactory.opensession ();
	}
}
Finished writing, then you can write a simple unit test ...

public class Contactdaotest {@Test public void testselectlist () {Contactdao dao = new Contactdaoimpl ();
		list<contact> list = Dao.query ();
		Assert.assertequals (3, List.size ());
		for (contact c:list) {System.out.println ("Name:" +c.getname () + ", DOB:" +c.getdob () + ", Email:" +c.getemail ());
		@Test public void Testselectbyname () {Contactdao dao = new Contactdaoimpl ();
		list<contact> list = Dao.query ("Tangerine");
		Assert.assertequals (1, list.size ());
		for (contact c:list) {System.out.println ("Name:" +c.getname () + ", DOB:" +c.getdob () + ", Email:" +c.getemail ());
		@Test public void Testfindcontact () {Contactdao dao = new Contactdaoimpl ();
		Contact Contact = Dao.find (9);
		Assert.assertnotnull (contact);
		Assert.assertequals ("SSSs", Contact.getname ());
	System.out.println ("Name:" +contact.getname ());
		@Test public void Testinsertcontact () {contacts = new contact ();
		Contact.setname ("MyBatis Test"); Contact.setaddress ("NewYork City,downTown ");
		Contact.setdob (New Date ());
		Contact.setgender ("M");
		Contact.setemail ("HelloBatis@gmail.com");
		Contactdao dao = new Contactdaoimpl ();
		int rows = Dao.insert (contact);
		System.out.println (rows+ "Rows effected!");
	Assert.assertequals (1, rows);
		@Test public void Testupdatecontact () {contacts = new contact ();
		Contact.setid (9);
		Contact.setname ("MyBatis Update");
		Contact.setaddress ("Shanghai,china");
		Contact.setdob (New Date ());
		Contact.setgender ("M");
		Contact.setemail ("mybatisworld@gmail.com");
		Contactdao dao = new Contactdaoimpl ();
		
	Dao.update (contact);
		@Test public void Testdeletecontact () {Contactdao dao = new Contactdaoimpl ();
			try{int rows = Dao.delete (5);
			Assert.assertequals (1, rows);
			Contact deleted = Dao.find (5);
		Assert.assertnull (deleted);
		}catch (Exception ex) {assert.fail (); }
	}

MyBatis or quite simple, is to remember more rules, more technical, the head is full of rules ....




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.