Project Build Series II: Configure MyBatis and springmvcmybatis in SpringMVC framework

Source: Internet
Author: User

Project Build Series II: Configure MyBatis and springmvcmybatis in SpringMVC framework
1. What is MyBatis?

MyBatis is a supportedNormalSQLQuery,Stored ProcedureAndAdvanced ingExcellentPersistence Layer framework. MyBatis eliminates the manual setup of almost all JDBC code and parameters and retrieval encapsulation of result sets. MyBatis can be used easilyXML or annotationIt is used for configuration and original ing to map interfaces and Java POJO (Plain Old Java Objects, common Java Objects) into records in the database.

Go back to directory 2 and prepare the environment
  • After setting up the SpringMVC framework, you can read "one of the project building series: Building a SpringMVC project using Maven" or download it directly from my GitHub.
  • Add jar package

[M]YBatis]

<!-- mybatis begin --><dependency>    <groupId>org.mybatis</groupId>    <artifactId>mybatis</artifactId>    <version>3.2.3</version></dependency><!-- mybatis end -->    

MYSQL driver package]

<dependency>    <groupId>mysql</groupId>    <artifactId>mysql-connector-java</artifactId>    <version>5.1.31</version></dependency>
  • Create a database
CREATE DATABASE mybatis_test;USE mybatis_test;CREATE TABLE user (  name varchar(50) CHARACTER SET utf8 DEFAULT NULL,  age int(11) DEFAULT NULL,  UNIQUE KEY name (name)) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Go back to directory 3. Configure and use MyBatis
  • Create an object class User. java
package cn.jxufe.web.mybatis;public class User {    private String name;    private Integer age;    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public Integer getAge() {        return age;    }    public void setAge(Integer age) {        this.age = age;    }    public User(String name, Integer age) {        super();        this.name = name;        this.age = age;    }    public User() {        super();    }}
  • Create a usering file UserMapper. 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 ">
<! -- 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. -->
<Mapper namespace = "cn. jxufe. web. mybatis. UserMapper"> <! -- The namespace must be the path of the UserMapper interface, otherwise, "is not known to the MapperRegistry" --> <insert id = "insertUser" parameterType = "User"> insert into user (name, age) values (# {name}, # {age}) <! -- Here the SQL end cannot add points, otherwise the "ORA-00911" error --> </insert> <! -- Write the query SQL statement in the select tag and set the id attribute of the select tag to getUser. 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 --> <! -- The id here must be the same as the interface method name in the UserMapper interface, otherwise an error will be reported during running --> <select id = "getUser" resultType = "User" parameterType = "java. lang. string "> select * from user where name =#{ name} </select> </mapper>
  • Create an interface class UserMapper. java
package cn.jxufe.web.mybatis;public interface UserMapper {    public void insertUser(User user);    public User getUser(String name);}
  • Create profile mybatis-config.xml
<? 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> <settings> <! -- Changes from the defaults for testing --> <setting name = "cacheEnabled" value = "false"/> <setting name = "useGeneratedKeys" value = "true"/> <setting name = "defaultExecutorType" value = "REUSE"/> </settings> <typeAliases> <typeAlias alias = "User" type = "cn. jxufe. web. mybatis. user "/> </typeAliases> <environments default =" development "> <environment id =" development "> <transactionManager type =" jdbc "/>
<! -- Configure database connection information --> <dataSource type = "POOLED"> <property name = "driver" value = "com. mysql. jdbc. driver "/> <property name =" url "value =" jdbc: mysql: // 127.0.0.1: 3306/mybatis_test "/> <property name =" username "value =" root "/> <property name =" password "value =" 123456 "/> </dataSource> </ environment> </environments> <mappers> <! -- Register the UserMapper. xml file --> <mapper resource = "mappers/UserMapper. xml"/> </mappers> </configuration>
  • Create a tool class MyBatisUtil. java to create a SqlSessionFactory instance. Each database corresponds to a SqlSessionFactory instance.
package cn.jxufe.web.mybatis;import java.io.IOException;import java.io.Reader;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;public class MyBatisUtil {    private final static SqlSessionFactory sqlSessionFactory;    static {        String resource = "mybatis-config.xml";        Reader reader = null;        try {            reader = Resources.getResourceAsReader(resource);        } catch (IOException e) {            System.out.println(e.getMessage());        }        sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);    }    public static SqlSessionFactory getSqlSessionFactory() {        return sqlSessionFactory;    }}
  • Test Call
Package cn. jxufe. web. mybatis; import org. apache. ibatis. session. sqlSession; import org. apache. ibatis. session. sqlSessionFactory; public class TestMyBatis {static SqlSessionFactory sqlSessionFactory = null; static {sqlSessionFactory = MyBatisUtil. getSqlSessionFactory ();} // public static void main (String [] args) {// testAdd (); // getUser (); //} public static void testAdd () {SqlSession sqlSession = sqlSessionFactory. openSession (); try {UserMapper userMapper = sqlSession. getMapper (UserMapper. class); User user = new User ("lisi", new Integer (25); userMapper. insertUser (user); sqlSession. commit (); // you must submit it here, otherwise the data cannot be imported into the database} finally {sqlSession. close () ;}} public static void getUser () {SqlSession sqlSession = sqlSessionFactory. openSession (); try {UserMapper userMapper = sqlSession. getMapper (UserMapper. class); User user = userMapper. getUser ("lisi"); System. out. println ("name:" + user. getName () + "| age:" + user. getAge ();} finally {sqlSession. close ();}}}
  • Project directory structure

  • Test Results

See the following documents:

Http://www.spring.net

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.