The first MyBatis program and the first mybatis Program

Source: Internet
Author: User

The first MyBatis program and the first mybatis Program

I recently studied some MyBatis technologies. Although I haven't used them yet, I think it is good to understand them. Here I recorded the first simple Demo program to prevent myself from forgetting it.

Step 1 needs to configure the Mybatis-config.xml file. note: two methods are used to map object classes. in <Mapper>, the first User object is mapped in XMl format, and the second Category is mapped using the annotation CategoryMappper format.

<? 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> <properties resource = "jdbc. properties"> </properties> <! -- <TypeAliases> <package name = "com. mybatis02.model "/> </typeAliases> --> <environments default =" devEnvironment "> <environment id =" devEnvironment "> <transactionManager type =" JDBC "> </transactionManager> <dataSource type = "POOLED"> <property name = "driver" value = "$ {dirver}"/> <property name = "url" value = "$ {url}"/> <property name = "username" value = "$ {username}"/> <property name = "password" value = "$ {passwor D} "/> </dataSource> </environment> </environments> <mappers> <! -- Map User objects in XML format --> <mapper resource = "com/mybatis02/model/User. xml"/> <! -- Map Category in Annotation mode --> <mapper class = "com. mybatis02.mapper. CategoryMapper"/> </mappers> </configuration>

Step 2 analyze the mybatis-config.xml

public class MyBatisUtil {    private static SqlSessionFactory factory;    static{        try {            InputStream in = Resources.class.getResourceAsStream("mybatis-config.xml");            factory = new SqlSessionFactoryBuilder().build(in);        } catch (Exception e) {            e.printStackTrace();        }    }        public static SqlSession createSession(){        return factory.openSession();    }        public static void closeSession(SqlSession session){        if (session != null) {            session.close();        }    }}

The following describes the xml format and annotation method in the following two ways:

XML format:

1. 1. Create object class User (the get and set methods are omitted here)

public class User {    private int id;    private String username;    private String password;    private String nickname;    private int type;    private List<Address> addresses;    ...}

1. 2. create an xml User ing file for the User object. note that the full path of the User class must be configured for the namespace attribute. an Insert operation with the id of add is defined. its Parameter type (parameterType) is a User object

<?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"><mapper namespace="com.mybatis02.model.User">    <insert id="add" parameterType="com.mybatis02.model.User">        insert t_user(id,username,password,nickname,type)        values(#{id},#{username},#{password},#{nickname},#{type})    </insert></mapper>

1. 3. Test the XML ing method

@ Test public void testAdd () {// 1. create Mybatis configuration file input stream InputStream in = null; try {in = Resources. getResourceAsStream ("mybatis-config.xml");} catch (IOException e) {// TODO Auto-generated catch block e. printStackTrace ();} // 2. create SqlSessionFactory factory = new SqlSessionFactoryBuilder (). build (in); // 3. create SQlSession SqlSession session = factory. openSession (); // 4. call the UserMapper file to insert the object into the database (before calling the file, you need to add the mapper file to the mybatis-config.xml) User user User = new user (); User. setId (8); user. setUsername ("Zhang Fei"); user. setPassword ("123"); user. setNickname ("James"); user. setType (1); session. insert ("com. mybatis02.model. user. add ", user); session. commit (); session. close ();}

Compile the demo for the annotation ing method.

2. 1. Create the same object class

public class Category {    private int id;    private String name;        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;    }}

2.2 create a CategoryMapper er ing Class and create an add method. add the Insert operation to the method and execute the corresponding SQL statement.

This file is introduced to the mybatis-config.xml in step 1.

 <mapper class="com.mybatis02.mapper.CategoryMapper"/>
public interface CategoryMapper {    @Insert("insert into t_category(id,name) value (#{id},#{name})")    public void add(Category category);    }

2.3 Test

@ Test public void testCategory () {// 1. create Mybatis configuration file input stream InputStream in = null; try {in = Resources. getResourceAsStream ("mybatis-config.xml");} catch (IOException e) {// TODO Auto-generated catch block e. printStackTrace ();} // 2. create SqlSessionFactory factory = new SqlSessionFactoryBuilder (). build (in); // 3. create SQlSession SqlSession session = factory. openSession (); // 4. call the CategoryMapper interface to insert objects into the database (you need to add the ER er file to the mybatis-config.xml before calling the file) Category category = new Category (); category. setId (1); category. setName ("Clothes"); session. insert ("com. mybatis02.mapper. categoryMapper. add ", category); session. commit (); session. close ();}

Feeling: I first wrote the demo and reported an error. I mixed the xml method ing with the annotation method ing. I got half of the two methods and reported various errors.

If you encounter problems in the future, you must repeat them step by step to keep the logic clear so that you can locate and correct errors more accurately.


When you use myBatis to insert data, the program runs normally, but the data is not added to the database.

GetSqlMapClientTemplate (). insert ("Users. addUser", user); no added operations

How can spring integrate Program-based transactions in mybatis?

You have asked me a lot about fuzzy search. spring can perform programmatic transactions. A programmatic transaction is not a jdbc six-step transaction. You can also perform jdbc transactions in spring. What are you doing with mybatis, do you want spring + mybatis integration? How do you configure transactions in the configuration file?

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.