MyBatils course 1: MyBatils Course

Source: Internet
Author: User

MyBatils course 1: MyBatils Course

MyBatis is an excellent persistent layer framework that supports common SQL queries, stored procedures, and advanced mappings. MyBatis eliminates the manual settings of almost all JDBC code and parameters and retrieves the result set. MyBatis uses simple XML or annotations for configuration and original ing. It maps interfaces and Java POJOs (Plain Old Java Objects, a common Java object) into records in the database.

Each MyBatis application mainly uses SqlSessionFactory instances. A SqlSessionFactory instance can be obtained through SqlSessionFactoryBuilder. SqlSessionFactoryBuilder can be obtained from an xml configuration file or an instance of a predefined configuration class.

Creating a SqlSessionFactory instance using an xml file is very simple. We recommend that you use the classpath resource in this configuration, but you can use any Reader instance, including instances created using a url starting with a file path or file. MyBatis has a category class ---- Resources, which has many methods to easily load Resources from the class path and other locations.

Build a development environment:Mybatis-3.1.1.jar and mysql-connector-java-5.1.7-bin.jar

  • Configuration file:

1. Set the mybatis configuration file: SQLMapconfig. xml. Create this file in the src directory (the file name is arbitrary and the format is. xml ):

 

The content is 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"><configuration>    <typeAliases>        <typeAlias alias="User" type="com.yiibai.mybatis.models.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://127.0.0.1:3306/yiibai" />                <property name="username" value="root" />                <property name="password" value="" />                       </dataSource>        </environment>    </environments>    <mappers>         <mapper resource="com/yiibai/mybatis/models/User.xml" />    </mappers></configuration>

2. Define the object class corresponding to the table,As shown in:

 

Package org.wangyi.com; import java. text. simpleDateFormat; import java. util. date; /*** define the object class ** @ author wangyi * @ version 1.0 <br/> * <a href = "www.baidu.com"> Baidu </a> */public class User {private int id; private String username; private Date birthday; private String sex; private String address; 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 Date getBirthday () {return birthday;} public void setBirthday (Date birthday) {this. birthday = birthday;} public String getSex () {return sex;} public void setSex (String sex) {this. sex = sex;} public String getAddress () {return address;} public void setAddress (String address) {this. address = address ;}@ Override public String toString () {SimpleDateFormat format = new SimpleDateFormat ("yyyy-MM-dd"); String bd = format. format (this. birthday); String content = "User [" + this. id + "," + this. username + "," + this. sex + "," + bd + "," + this. address + "]"; return content ;}}

 

3. Define the SQL ing file userMapper. xml for operating the users table

Create a me. gacl. mapping package to store the SQL ing file. Create a userMapper. xml file in the package, as shown in:

<? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE mapper PUBLIC "-// mybatis.org//DTD Mapper 3.0 //" http://mybatis.org/dtd/mybatis-3-mapper.dtd "> <! -- Specify a unique namespace for this mapper. Set the namespace value to the package name + SQL ing file name. This ensures that the namespace value is unique, for example, namespace = "me. gacl. mapping. userMapper "is me. gacl. mapping (package name) + userMapper (userMapper. remove the Suffix from the xml file) --> <mapper namespace = "org. wangyi. mapping. userMapper "> <! -- Write the query SQL statement in the select tag and set the id attribute of the select tag to finduserByid. The id attribute value must be unique, the parameterType attribute cannot be used repeatedly to specify the parameter type used for query. The resultType attribute specifies the type of the returned result set resultType = "org.wangyi.com. "User" indicates that the query result is encapsulated into an object of the User class. The returned User class is the entity class corresponding to the users table --> <! -- Query by id to obtain a user object --> <select id = "finduserByid" parameterType = "int" resultType = "org.wangyi.com. user "> select * from user where id =#{ id} </select> </mapper>

 

 

The following is a description of these configuration files:
1. Configuration FileSQLMapconfig. xml. Xml is mybatis used to create sessionFactory, which mainly contains the database connection content and the alias corresponding to the java class, such as: <typeAlias alias = "User" type = "org. wangyi. mapping. userMapperr "/> this alias is very important. In the ing of a specific class, for example, User. in xml, the resultType corresponds to this type. To ensure consistency, the resultType here has another separate definition method. We will introduce it in detail later.
2. <mapper resource = "com/yiibai/mybatis/models/User. xml"/> In SQLMapconfig. xml is an xml configuration file containing the class to be mapped.
3. The userMapper. xml file mainly defines various SQL statements, parameters of these statements, and types to be returned.

Start testing

Package org. wangy. first; import java. io. fileInputStream; import java. io. IOException; import java. io. inputStream; 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 org.wangyi.com. user; /*** MyBatis entry-level program ** @ author wangyi * @ version 1.0 <br/> * <a href = "www.baidu.com"> Baidu </a> **/public class MyBatisFirst {// query a record @ Test public void findUserByid () throws IOException {// MyBatis configuration file String resource = "SQLMapConfig. xml "; // obtain SQLMapConfig. xml configuration file stream String path = MyBatisFirst. class. getClassLoader (). getResource (resource ). getPath (); InputStream inputStream = new FileInputStream (path); // use the Resources class provided by MyBatis to load the configuration file of mybatis (It also loads the associated ing file) // Reader reader = Resources. getResourceAsReader (resource) or // InputStream inputStream = Resources. getResourceAsStream (resource); // create the session factory SqlSessionFactory factory of MyBatis = new SqlSessionFactoryBuilder (). build (inputStream); // obtain the session sqlSession SqlSession sqlSession = factory. openSession (); // operate the database through sqlSession/*** first parameter: value = xxxMapper. the namespace attribute value of the ER er tag in the xml file + ". "+ id value of the SQL statement label, * second parameter: value = parameter of the ResultType that matches the ing file */User user User = sqlSession. selectOne ("org. wangyi. mapping. userMapper. finduserByid ", 31); // release the resource. Do not forget sqlSession. close (); System. out. println (user );}}

Related Article

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.