MyBatis usage (Configuration and annotation usage)

Source: Internet
Author: User
Tags generator create database

MyBatis is a persistent layer framework usage (xml-based configuration) 1. Add Dependencies (Maven)

<!--database related, MySQL, mybatis--> <!--JDBC Connection--> <dependency> <groupid>mysql</groupid > <artifactId>mysql-connector-java</artifactId> <version>5.1.37</version> & lt;/dependency> <!--spring-mybatis--> <dependency> <groupid>org.mybatis</groupid > <artifactId>mybatis-spring</artifactId> <version>${mybatis-spring-version}</vers Ion> </dependency> <!--mybatis--> <dependency> <groupid>org.mybatis</gro
    Upid> <artifactId>mybatis</artifactId> <version>${mybatis-version}</version> </dependency> <!--reflection Generation entity class--> <dependency> <groupid>org.mybatis.generator</gr 
    Oupid> <artifactId>mybatis-generator-core</artifactId> <version>1.3.2</version> </dependency> 

2. Establish database, table
CREATE DATABASE testdatabase;
Use Testdatabase;
CREATE TABLE User (id int PRIMARY KEY auto_increment, userName VARCHAR not NULL, userage INT not NULL);
INSERT into User (UserName, userage) VALUES (' xiaoxin ',);
INSERT into User (UserName, userage) VALUES (' xiaoming ', 22);
3. Entity classes for tables
Package com.xiaoxin.demo.dto;

public class User {
	private int id;
    Private String userName;
    private int userage;
	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 int getuserage () {return
		userage;
	}
	public void setuserage (int userage) {
		this.userage = userage;
	}
	@Override public
	String toString () {return
		"User [id=" + ID + ", username=" + UserName + ", userage=" + userage + "]";
	}
}

4. Add a MyBatis profile
<?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> <typeAliases> <typealias alias= "User" type= "Com.xiaoxin.demo.dto.User"/> </typeAliases> <!--database environment configuration--> <environments default= "Development" > <environment id= "Development" > <!--JDBC Management--> <transactionmanager type= "jdbc"/> <!--what connection pool to use--&G
            T <datasource type= "Pooled" > <!--JDBC driver--> <property name= "Driver" value= . jdbc. Driver "/> <!--database name url--> <property name=" url "value=" jdbc:mysql://127.0.0.1:3306/tes Tdatabase "/> <!--database user--> <property name=" username "value=" root "/> &L t;!
     --Database user password--> <property name= "password" value= ""/>       </dataSource> </environment> </environments> <!--register User.xml to MyBatis's profile, Us Er.xml Configure--> <mappers> <mapper resource= "Com/xiaoxin/demo/dto/user.xml"/> </mappers&gt
; </configuration>

5. Define the mapping file to manipulate the user table, and step fourth has been registered in the MyBatis configuration file.
<?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" >
<!--Define SQL mapping files that manipulate the user table Usermapper.xml  -->
<mapper namespace= "Com.xiaoxin.demo.dto" >
    <select id= "Selectuserbyid" parametertype= "int" resulttype= "user" >
        select * from ' user ' where id = #{id}
    & Lt;/select>
</mapper>

6. Test
Package com.xiaoxin.demo.dto;

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;

public class TestUser {
	@Test public
	void TestUser () throws exception{
		 sqlsessionfactory sqlsessionfactory ;
	     Reader reader; 
	     String resource = "Spring/configuration.xml";
	     Load a stream
	     reader= resources.getresourceasreader (Resource);
	     Generate Sqlsessionfactory factory
	     sqlsessionfactory = new Sqlsessionfactorybuilder (). build (reader);
	     sqlsession session = Sqlsessionfactory.opensession ();
	     User user = (user) Session.selectone ("Com.xiaoxin.demo.dto.selectUserByID", 1);
	     System.out.print (User.tostring ());
	    Session.close ();
		
	}
	



Connect database successfully query to data

CRUD Operations Rollup
<?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" >
<!--Define SQL mapping files that manipulate the users table Usermapper.xml  -->
<mapper namespace= "Com.xiaoxin.demo.dto" >
    <!--query  -->
     <select id= "Selectuserall" parametertype= "int" resulttype= "User" >
        SELECT * From user
    </select>
    <!--insert  -->
    <insert id= "Insertuser parametertype=" Com.xiaoxin.demo.dto.User ">
    		insert INTO User (username,userage) VALUES (#{username},#{userage});
    </insert>
	<!--update  -->
    <update id= "UpdateUser" parametertype= " Com.xiaoxin.demo.dto.User ">
    		update User set Userage=#{userage},username=#{username} where Id=#{id}
    </update>
    <!--delete  -->
    <delete id= "deleteuser" parametertype= "int" >
    	Delete From user where Id=#{id}
    </delete>
    
</mapper>
Test
Package com.xiaoxin.demo.dto;
Import Java.io.Reader;

Import java.util.List;
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;
	     public class TestUser {@Test the public void TestUser () throws exception{sqlsessionfactory sqlsessionfactory; 
	     Reader reader;
	     String resource = "Spring/configuration.xml";
	     Load a stream reader= Resources.getresourceasreader (Resource);
	     Generate Sqlsessionfactory Factory sqlsessionfactory = new Sqlsessionfactorybuilder (). build (reader);
	     sqlsession session = Sqlsessionfactory.opensession ();
Insert//User user1 = new User ();
User1.setusername ("Xiaohong");
User1.setuserage (20);
Session.insert ("Com.xiaoxin.demo.dto.insertUser", user1);
Session.commit () Be sure to do otherwise there is no information in the database ....
	    Session.commit (); Update//Put Xiaohong's nameChange to Xiaohong101 age to Xiaohong ID is the//User User3 = new User ();
User3.setusername ("Xiaohong101");
User3.setuserage (44);
User3.setid (16);
Session.update ("Com.xiaoxin.demo.dto.updateUser", User3);
	     
	    Session.commit ();
	     Delete Session.delete ("Com.xiaoxin.demo.dto.deleteUser", 16);
	     Session.commit ();
	     Query database All the information list<user> user2 = session.selectlist ("Com.xiaoxin.demo.dto.selectUserAll");
	     for (User user:user2) {System.out.println (user.tostring ());
		
	} session.close ();
 }
	

}
Above all the success of their own testing, but the process of XML configuration of their own mistakes a lot, debugging many times before successfully debugging out, the following learning based on annotation annotation usage of mybatis
1. Interface for defining SQL mappings
Package com.xiaoxin.demo.mapper;

Import java.util.List;

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.xiaoxin.demo.dto.User;

Public interface Usermapper {
	@Select (' select * from user ') public
	list<user> Getselectuser ();
	@Update ("Update user set Username=#{username},userage=#{userage} where Id=#{id}") Public
	void Getupdateuser (user user);
	@Insert (Insert into user (Username,userage) VALUES (#{username},#{userage}); "
	public void Getinsertuser (user user);
	@Delete (' Delete from user where Id=#{id} ') public
	void getdeleteuser (int id);
	

}
2. Register this mapping interface in the MyBatis configuration file (Note class ...). )
<mappers>
        <mapper resource= "Com/xiaoxin/demo/dto/user.xml"/>
        <mapper class= " Com.xiaoxin.demo.mapper.UserMapper "></mapper>
    </mappers>

Called in the DAO Class (here is the test)
Package com.xiaoxin.demo.dto;
Import java.io.IOException;
Import Java.io.Reader;

Import java.util.List;
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.xiaoxin.demo.mapper.UserMapper; public class Testuserannotation {@Test public void TestUser () throws ioexception{sqlsessionfactory sqlsessionf
	     Actory; 
	     Reader reader;
	     String resource = "Spring/configuration.xml";
	     Load a stream reader= Resources.getresourceasreader (Resource);
	     Generate Sqlsessionfactory Factory sqlsessionfactory = new Sqlsessionfactorybuilder (). build (reader);
	     
	     sqlsession session = Sqlsessionfactory.opensession ();
	     Usermapper usermapper = Session.getmapper (Usermapper.class);
Insert//USER user = new User ();
User.setusername ("Xinxin");
User.setuserage (20); UsermaPper.getinsertuser (user);
	     Session.commit ();
Delete//Usermapper.getdeleteuser (21);
	     Session.commit ();
Update will change the name of ID 19 to no change age to//user user = new User ();
User.setid (19);
User.setusername ("Xinxin");
User.setuserage (23);
Usermapper.getupdateuser (user);
	     Session.commit ();
	     Query list<user> users = Usermapper.getselectuser ();
	     for (User user2:users) {System.out.println (user2.tostring ());
	} session.close ();
 }

}

Test successful






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.