[Crazy guy Tom] mybatis.002 first query!

Source: Internet
Author: User
Reference
  • Note the notes in the following article.

  • Mybatis Getting Started: http://mybatis.github.io/mybatis-3/zh/getting-started.html

  • Source code download: (under review)

Code structure
1. config: configuration file directory 2. pojo: Bean class package 3. Controller: data interface 4. SQL: database source file

650) This. width = 650; "src =" http://s3.51cto.com/wyfs02/M01/49/CE/wKioL1Qa8lzCuQw_AADZPa0H6ng894.jpg "Title =" 001.png" alt = "wkiol1qa8lzcuqw_aadzpa0h6ng894.jpg"/>

Database creation
CREATE DATABASE  IF NOT EXISTS `mybatis`;USE `mybatis`;DROP TABLE IF EXISTS `users`;CREATE TABLE `users` (  `id` int(11) NOT NULL AUTO_INCREMENT,  `name` varchar(45) DEFAULT NULL,  `age` int(11) DEFAULT NULL,  `phone` varchar(45) DEFAULT NULL,  PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;LOCK TABLES `users` WRITE;INSERT INTO `users` VALUES (1,‘jimmy.song‘,22,‘13810001234‘),(2,‘sunspot‘,24,‘13812341234‘);UNLOCK TABLES;
Create a configuration for a linked Database

Location: CC/fozone/demo/mybatis/config/mybatis. config. xml

<? XML version = "1.0" encoding = "UTF-8"?> <! Doctype configurationpublic "-// mybatis.org//dtd config 3.0 //" http://mybatis.org/dtd/mybatis-3-config.dtd "> <configuration> <! -- Configure the database link --> <environments default = "development"> <environment id = "development"> <transactionmanager type = "JDBC"/> <datasource type = "pooled"> <! -- Database Link driver --> <property name = "driver" value = "org. gjt. Mm. MySQL. Driver"/> <! -- Database link --> <property name = "url" value = "JDBC: mysql: // localhost: 3306/mybatis? Charset = utf8 "/> <! -- Database account password --> <property name = "username" value = "root"/> <property name = "password" value = "root"/> </datasource> </ environment> </environments> <! -- List of configuration files mapped to the database --> <mappers> <mapper resource = "CC/fozone/demo/mybatis/config/mapper/user. mapper. XML "/> </mappers> </configuration>
Create user class

Location: CC/fozone/demo/mybatis/pojo/user. Java

package cc.fozone.demo.mybatis.pojo;public class User {    private int id;    private String name;    private int age;    private String phone;    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }    public String getPhone() {        return phone;    }    public void setPhone(String phone) {        this.phone = phone;    }    public String toString(){        return "{id:"+id+",name:"+name+",age:"+age+",phone:"+phone+"}";    }}
Create user data interface

Location: CC/fozone/demo/mybatis/controller/iusercontroller. Java

Package CC. fozone. demo. mybatis. controller; import Java. util. list; import CC. fozone. demo. mybatis. pojo. user; public interface iusercontroller {// query all users public list <user> getallusers (); // query user public user getuser (string phone) by phone );}
Create a user ing configuration for the user table

Location: CC/fozone/demo/mybatis/config/mapper/user. Mapper. xml

<? XML version = "1.0" encoding = "UTF-8"?> <! Doctype mapper public "-// mybatis.org//dtd mapper 3.0 //" http://mybatis.org/dtd/mybatis-3-mapper.dtd "> <! -- Namespace: match with the Controller Interface --> <mapper namespace = "cc. fozone. Demo. mybatis. Controller. iusercontroller"> <! -- User table ing type: Class address ID: instantiation id --> <resultmap type = "cc. fozone. demo. mybatis. pojo. user "id =" userresultmap "> <ID property =" ID "column =" ID "/> <result property =" name "column =" name "/> <result property = "Age" column = "Age"/> <result property = "phone" column = "phone"/> </resultmap> <! -- SELECT query statement ID: Unique Identifier, consistent with the Controller Interface Method resultmap: reference of the injected object in the queried data instantiation --> <select id = "getallusers" resultmap = "userresultmap"> <! [CDATA [select ID, name, age, phone from users]> </SELECT> <! -- # {PHONE}: parameter, consistent with the getuser method in controller. resulttype: the type of database instantiation injection to be queried. It cannot be used together with resultmap, however, we recommend that you use resultmap --> <select id = "getuser" resulttype = "cc. fozone. demo. mybatis. pojo. user "> <! [CDATA [select ID, name, age, phone from users where phone =#{ phone}]> </SELECT> </mapper>
Simulate service call

Location: CC/fozone/demo/mybatis/APP. Java

Package CC. fozone. demo. mybatis; import Java. io. ioexception; import Java. io. inputstream; 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 CC. fozone. demo. mybatis. controller. iusercontroller; import CC. fozone. demo. mybatis. pojo. user ;/*** Hello world! **/Public class app {// database link configuration Private Static final string Config = "CC/fozone/demo/mybatis/config/mybatis. config. XML "; // SQL session factory private sqlsessionfactory factory; Public app () {// initialize this. init ();} // initialize the SQL session factory private void Init () {inputstream input; try {input = resources. getresourceasstream (config); this. factory = new sqlsessionfactorybuilder (). build (input);} catch (ioexception e) {// todo auto-generated Catch Block E. printstacktrace () ;}/// query the public list of all users <user> getusers () {// open session sqlsession session = This. factory. opensession (); // instantiate the Controller object based on the ing. Here, the iusercontroller. the class is consistent with the namespace in the Mapper configuration. iusercontroller = session. getmapper (iusercontroller. class); // obtain the list of all users <user> List = controller. getallusers (); // closes the session. close (); return list;} // query the user's public user getuser (string phone) {user = NULL according to the phone number; // session sqlsession session = This. factory. opensession (); iusercontroller controller = session. getmapper (iusercontroller. class); // query the user. The input parameters here will be replaced by the # {PHONE} placeholder user = controller in mapper. getuser (phone); Session. close (); Return user ;}}
Create Test Cases

Location: CC/fozone/demo/mybatis/apptest. Java

package cc.fozone.demo.mybatis;import java.util.List;import org.junit.Before;import org.junit.Test;import static org.junit.Assert.*;import cc.fozone.demo.mybatis.pojo.User;public class AppTest {    private App app;    @Before    public void setUp() throws Exception {        app = new App();        assertNotNull(app);    }    @Test    public void testList() {        List<User> list = app.getUsers();        assertEquals(2,list.size());    }        @Test    public void testUser(){        User user = app.getUser("13810001234");        assertNotNull(user);        assertEquals("jimmy.song", user.getName());    }}


Result

Right-click the apptest. Java file and choose "run"> "JUnit test ".

650) This. width = 650; "src =" http://s3.51cto.com/wyfs02/M02/49/CD/wKiom1Qa967AeyyNAABvYTHZCHs588.jpg "Title =" 002.png" alt = "wkiom1qa967aeyynaabvythzchs588.jpg"/>

This article from "Bo yuan to Jing" blog, please be sure to keep this source http://sunspot.blog.51cto.com/372554/1554965

[Crazy guy Tom] mybatis.002 first query!

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.