mybatis CRUD

What is MyBatis?

MyBatis persistence framework is to support outstanding ordinary SQL queries, stored procedures and advanced mappings. MyBatis eliminates almost all manual settings and parameters JDBC code and retrieve the result set. MyBatis can use simple XML or Annotations for configuration and map primitives, Map interfaces and Java POJO (Plain Old Java Objects, ordinary Java Objects) to database records in.

MyBatis Download: https: //github.com/mybatis/mybatis-3/releases

Mybatis examples

CRUD operations of a User table:

User表:

-- ----------------------------
-- Table structure for `user`
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `userName` varchar(50) DEFAULT NULL,
  `userAge` int(11) DEFAULT NULL,
  `userAddress` varchar(200) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'summer', '30', 'shanghai');
INSERT INTO `user` VALUES ('2', 'test2', '22', 'suzhou');
INSERT INTO `user` VALUES ('3', 'test1', '29', 'some place');
INSERT INTO `user` VALUES ('4', 'lu', '28', 'some place');
INSERT INTO `user` VALUES ('5', 'xiaoxun', '27', 'nanjing');
 

Build a mybatis in the Src directory xml configuration file Configuration.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>
    <!-- mybatis别名定义 -->
    <typeAliases> 
        <typeAlias alias="User" type="com.mybatis.test.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/mybatis" />
            <property name="username" value="root"/>
            <Property name = "password" value = "ADMIN" /> 
            </ the dataSource> 
        </ Environment> 
    </ Environments> 
    
    <-! mapper MyBatis of files, each corresponding to a xml configuration file Interface -> 
    <by mappers> 
        < = Resource Mapper "COM / MyBatis / Test / User.xml" /> 
    </ by mappers> 
</ Configuration>

User mappers defined profile of User.xml

<? xml Version = "1.0" encoding = "UTF-8"?> 
<DOCTYPE Mapper the PUBLIC! "- // mybatis.org//DTD Mapper 3.0 // EN" 
"http://mybatis.org/dtd/mybatis mapper.dtd--3 "> 

<Mapper namespace =" com.mybatis.test.IUserOperation "> 

    <-! SELECT statement -> 
    <SELECT ID =" selectUserByID "the parameterType =" int "= the resultType" the User "> 
        SELECT WHERE user` from the user.id `* # = {ID} 
    </ SELECT> 
    
    <-! defined resultMap, can solve the problem of inconsistency of the class attribute names and database column name -> 
    <-! <the resultMap type =" the User "ID =" userResultMap "> 
        <Property ID =" ID "column =" user_id "/> 
        <= Result Property"userName" column="user_userName"  />
        <result property="userAge" column="user_userAge"  />
        <Property Result = "userAddress" column = "user_userAddress" /> 
    </resultMap> -->
    
    <-! return list select statement, attention is directed to the front resultMap value defined -> 
    <-! <select ID = "selectUsersByName" the parameterType = "String" The resultMap = "userResultMap"> 
        SELECT * WHERE User user.username from the userName = # {} 
    </ SELECT> -> 
    
    <SELECT ID = "selectUsersByName" the parameterType = "String" the resultType = "the User"> 
        SELECT * from # = {WHERE user.username User the userName} 
    </ SELECT> 
    
    <-! execute SQL statements increase operation. id and parameterType coincide with addUser method IUserOperation interface names and parameter types. 
    useGeneratedKeys set to "true" indicates that the primary key to obtain MyBatis automatically generated by the database; keyProperty = "id" 
        useGeneratedKeys = "true" the keyProperty = "id">
             values(#{userName},#{userAge},#{userAddress})  
    </insert>
    
    <update id="updateUser" parameterType="User" >
        update user set userName=#{userName},userAge=#{userAge},userAddress=#{userAddress} where id=#{id}
    </update>
    
    <delete id="deleteUser" parameterType="int">
        delete from user where id=#{id}
    </delete>
    
</mapper>

Profiles achieve the mapping between the interface and SQL statements. selectUsersByName uses two kinds of ways, but also a realization commented, using resultMap can attribute mapping and database column names good relationship is defined, property as a property class, column is a column name of the table, it can also be a table column names alias!

User class definition:

package com.mybatis.test;

public class User {
    
    private int id;
    private String userName;
    private int userAge;
    private String userAddress;
    
    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;
    }
    
    public String getUserAddress() {
        return userAddress;
    }
    
    public void setUserAddress(String userAddress) {
        this.userAddress = userAddress;
    }
    
    @Override
    public String toString(){
        return this.userName+" "+this.userAge+" "+this.userAddress;
    }

}
 

IUserOperaton definition:

 
package com.mybatis.test;

import java.util.List;

public interface IUserOperation {
    
    public User selectUserByID(int id);
    
    public List<User> selectUsersByName(String userName);
    
    public void addUser(User user);
    
    public void updateUser(User user);
    
    public void deleteUser(int id);
    
}
 

IUserOperation operation of the operation corresponding to the id of the interface, and the function name mybatis xml configuration file.

Test class Test:

 
package com.mybatis.test;

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;

public class Test {

    private static SqlSessionFactory sqlSessionFactory;
    private static Reader reader;

    static {
        try {
            reader = Resources.getResourceAsReader("Configuration.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static SqlSessionFactory getSession() {
        return sqlSessionFactory;
    }

    public void getUserByID(int userID) {
        SqlSession session = sqlSessionFactory.openSession();
        try {
            IUserOperation userOperation = session
                    .getMapper(IUserOperation.class);
            User user = userOperation.selectUserByID(userID);
            if (user != null) {
                System.out.println(user.getId() + ":" + user.getUserName()
                        + ":" + user.getUserAddress());
            }

        } finally {
            session.close();
        }
    }

    public void getUserList(String userName) {
        SqlSession session = sqlSessionFactory.openSession();
        try {
            IUserOperation userOperation = session
                    .getMapper(IUserOperation.class);
            List<User> users = userOperation.selectUsersByName(userName);
            for (User user : users) {
                System.out.println(user.getId() + ":" + user.getUserName()
                        + ":" + user.getUserAddress());
            }

        } finally {
            session.close();
        }
    }

    /**
     * 增加后要commit
     */
    public void addUser() {
        User user = new User();
        user.setUserAddress("place");
        user.setUserName("test_add");
        user.setUserAge(30);
        SqlSession session = sqlSessionFactory.openSession();
        try {
            IUserOperation userOperation = session
                    .getMapper(IUserOperation.class);
            userOperation.addUser(user);
            session.commit();
            System.out.println("新增用户ID:" + user.getId());
        } finally {
            session.close();
        }
    }

    /**
     * 修改后要commit
     */
    public void updateUser() {
        SqlSession session = sqlSessionFactory.openSession();
        try {
            IUserOperation userOperation = session
                    .getMapper(IUserOperation.class);
            User user = userOperation.selectUserByID(1);
            if (user != null) {
                user.setUserAddress("A new place");
                userOperation.updateUser(user);
                session.commit();
            }
        } finally {
            session.close();
        }
    }

    /**
     * 删除后要commit.
     * 
     * @param id
     */
    public void deleteUser(int id) {
        SqlSession session = sqlSessionFactory.openSession();
        try {
            IUserOperation userOperation = session
                    .getMapper(IUserOperation.class);
            userOperation.deleteUser(id);
            session.commit();
        } finally {
            session.close();
        }
    }

    public static void main(String[] args) {
        try {
            Test test = new Test();
            // test.getUserByID(1);
            // test.getUserList("test1");
            // test.addUser();
            // test.updateUser();
            // test.deleteUser(6);

        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

}
 

 MyBatis Mapper single parameter, parameter passing plurality of difference parameters

1, a single parameter

mybatis do not treat
# parameter name {/} any name: Remove the parameter value.

In the interface EmployeeMapper.javathere in

public Employee getEmpById(Integer id);

EmployeeMapper.xmlBy #{id}extraction parameter value, because only one, arbitrary names may be as follows:

<select id="getEmpById" resultType="com.atguigu.mybatis.bean.Employee">
         select * from tbl_employee where id = #{abcde}
</select>

2, a plurality of parameters

mybatis will do special treatment

We are the interface EmployeeMapper.javaa new method added:

public Employee getEmpByIdAndLastName(Integer id,String lastName); 

Value Method: The #{id},#{lastName}extraction parameters in this manner

<select id="getEmpByIdAndLastName" resultType="com.atguigu.mybatis.bean.Employee">
        select * from tbl_employee where id = #{id} and last_name=#{lastName}
    </select>

Abnormal results of:

    org.apache.ibatis.binding.BindingException: 
    Parameter 'id' not found. 
    Available parameters are [1, 0, param1, param2]

[Named Parameters: Packaging explicitly specified parameters:

public Employee getEmpByIdAndLastName(@Param("id") Integer id, @Param("lastName") String lastName);

Thus by #{id},#{lastName}extraction of the parameters in this way:

<select id="getEmpByIdAndLastName" resultType="com.atguigu.mybatis.bean.Employee">
        select * from tbl_employee where id = #{id} and last_name=#{lastName}
</select>
  

What is MyBatis?

MyBatis persistence framework is to support outstanding ordinary SQL queries, stored procedures and advanced mappings. MyBatis eliminates almost all manual settings and parameters JDBC code and retrieve the result set. MyBatis can use simple XML or Annotations for configuration and map primitives, Map interfaces and Java POJO (Plain Old Java Objects, ordinary Java Objects) to database records in.

MyBatis Download: https: //github.com/mybatis/mybatis-3/releases

Mybatis examples

CRUD operations of a User table:

User表:

-- ----------------------------
-- Table structure for `user`
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `userName` varchar(50) DEFAULT NULL,
  `userAge` int(11) DEFAULT NULL,
  `userAddress` varchar(200) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'summer', '30', 'shanghai');
INSERT INTO `user` VALUES ('2', 'test2', '22', 'suzhou');
INSERT INTO `user` VALUES ('3', 'test1', '29', 'some place');
INSERT INTO `user` VALUES ('4', 'lu', '28', 'some place');
INSERT INTO `user` VALUES ('5', 'xiaoxun', '27', 'nanjing');
 

Build a mybatis in the Src directory xml configuration file Configuration.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>
    <!-- mybatis别名定义 -->
    <typeAliases> 
        <typeAlias alias="User" type="com.mybatis.test.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/mybatis" />
            <property name="username" value="root"/>
            <Property name = "password" value = "ADMIN" /> 
            </ the dataSource> 
        </ Environment> 
    </ Environments> 
    
    <-! mapper MyBatis of files, each corresponding to a xml configuration file Interface -> 
    <by mappers> 
        < = Resource Mapper "COM / MyBatis / Test / User.xml" /> 
    </ by mappers> 
</ Configuration>

User mappers defined profile of User.xml

<? xml Version = "1.0" encoding = "UTF-8"?> 
<DOCTYPE Mapper the PUBLIC! "- // mybatis.org//DTD Mapper 3.0 // EN" 
"http://mybatis.org/dtd/mybatis mapper.dtd--3 "> 

<Mapper namespace =" com.mybatis.test.IUserOperation "> 

    <-! SELECT statement -> 
    <SELECT ID =" selectUserByID "the parameterType =" int "= the resultType" the User "> 
        SELECT WHERE user` from the user.id `* # = {ID} 
    </ SELECT> 
    
    <-! defined resultMap, can solve the problem of inconsistency of the class attribute names and database column name -> 
    <-! <the resultMap type =" the User "ID =" userResultMap "> 
        <Property ID =" ID "column =" user_id "/> 
        <= Result Property"userName" column="user_userName"  />
        <result property="userAge" column="user_userAge"  />
        <Property Result = "userAddress" column = "user_userAddress" /> 
    </ resultMap> -> 
    
    <-! return list select statement, attention is directed to the front resultMap value defined -> 
    <-! <select = ID "selectUsersByName" the parameterType = "String" The resultMap = "userResultMap"> 
        SELECT * WHERE User user.username from the userName = # {} 
    </ SELECT> -> 
    
    <SELECT ID = "selectUsersByName" the parameterType = "String" = the resultType "the User"> 
        SELECT * WHERE User user.username from the userName = # {} 
    </ SELECT> 
    
    <-! execute SQL statements increase operation. id and parameterType coincide with addUser method IUserOperation interface names and parameter types. 
    useGeneratedKeys set to "true"
        useGeneratedKeys="true" keyProperty="id"> 
        insert into user(userName,userAge,userAddress)  
             values(#{userName},#{userAge},#{userAddress})  
    </insert>
    
    <update id="updateUser" parameterType="User" >
        update user set userName=#{userName},userAge=#{userAge},userAddress=#{userAddress} where id=#{id}
    </update>
    
    <delete id="deleteUser" parameterType="int">
        delete from user where id=#{id}
    </delete>
    
</mapper>

Profiles achieve the mapping between the interface and SQL statements. selectUsersByName uses two kinds of ways, but also a realization commented, using resultMap can attribute mapping and database column names good relationship is defined, property as a property class, column is a column name of the table, it can also be a table column names alias!

User class definition:

package com.mybatis.test;

public class User {
    
    private int id;
    private String userName;
    private int userAge;
    private String userAddress;
    
    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;
    }
    
    public String getUserAddress() {
        return userAddress;
    }
    
    public void setUserAddress(String userAddress) {
        this.userAddress = userAddress;
    }
    
    @Override
    public String toString(){
        return this.userName+" "+this.userAge+" "+this.userAddress;
    }

}
 

IUserOperaton definition:

 
package com.mybatis.test;

import java.util.List;

public interface IUserOperation {
    
    public User selectUserByID(int id);
    
    public List<User> selectUsersByName(String userName);
    
    public void addUser(User user);
    
    public void updateUser(User user);
    
    public void deleteUser(int id);
    
}
 

IUserOperation operation of the operation corresponding to the id of the interface, and the function name mybatis xml configuration file.

Test class Test:

 
package com.mybatis.test;

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;

public class Test {

    private static SqlSessionFactory sqlSessionFactory;
    private static Reader reader;

    static {
        try {
            reader = Resources.getResourceAsReader("Configuration.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static SqlSessionFactory getSession() {
        return sqlSessionFactory;
    }

    public void getUserByID(int userID) {
        SqlSession session = sqlSessionFactory.openSession();
        try {
            IUserOperation userOperation = session
                    .getMapper(IUserOperation.class);
            User user = userOperation.selectUserByID(userID);
            if (user != null) {
                System.out.println(user.getId() + ":" + user.getUserName()
                        + ":" + user.getUserAddress());
            }

        } finally {
            session.close();
        }
    }

    public void getUserList(String userName) {
        SqlSession session = sqlSessionFactory.openSession();
        try {
            IUserOperation userOperation = session
                    .getMapper(IUserOperation.class);
            List<User> users = userOperation.selectUsersByName(userName);
            for (User user : users) {
                System.out.println(user.getId() + ":" + user.getUserName()
                        + ":" + user.getUserAddress());
            }

        } finally {
            session.close();
        }
    }

    /**
     * 增加后要commit
     */
    public void addUser() {
        User user = new User();
        user.setUserAddress("place");
        user.setUserName("test_add");
        user.setUserAge(30);
        SqlSession session = sqlSessionFactory.openSession();
        try {
            IUserOperation userOperation = session
                    .getMapper(IUserOperation.class);
            userOperation.addUser(user);
            session.commit();
            System.out.println("新增用户ID:" + user.getId());
        } finally {
            session.close();
        }
    }

    /**
     * 修改后要commit
     */
    public void updateUser() {
        SqlSession session = sqlSessionFactory.openSession();
        try {
            IUserOperation userOperation = session
                    .getMapper(IUserOperation.class);
            User user = userOperation.selectUserByID(1);
            if (user != null) {
                user.setUserAddress("A new place");
                userOperation.updateUser(user);
                session.commit();
            }
        } finally {
            session.close();
        }
    }

    /**
     * 删除后要commit.
     * 
     * @param id
     */
    public void deleteUser(int id) {
        SqlSession session = sqlSessionFactory.openSession();
        try {
            IUserOperation userOperation = session
                    .getMapper(IUserOperation.class);
            userOperation.deleteUser(id);
            session.commit();
        } finally {
            session.close();
        }
    }

    public static void main(String[] args) {
        try {
            Test test = new Test();
            // test.getUserByID(1);
            // test.getUserList("test1");
            // test.addUser();
            // test.updateUser();
            // test.deleteUser(6);

        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

}
 

 MyBatis Mapper single parameter, parameter passing plurality of difference parameters

1, a single parameter

mybatis do not treat
# parameter name {/} any name: Remove the parameter value.

In the interface EmployeeMapper.javathere in

public Employee getEmpById(Integer id);

EmployeeMapper.xmlBy #{id}extraction parameter value, because only one, arbitrary names may be as follows:

<select id="getEmpById" resultType="com.atguigu.mybatis.bean.Employee">
         select * from tbl_employee where id = #{abcde}
</select>

2, a plurality of parameters

mybatis will do special treatment

We are the interface EmployeeMapper.javaa new method added:

public Employee getEmpByIdAndLastName(Integer id,String lastName); 

Value Method: The #{id},#{lastName}extraction parameters in this manner

<select id="getEmpByIdAndLastName" resultType="com.atguigu.mybatis.bean.Employee">
        select * from tbl_employee where id = #{id} and last_name=#{lastName}
    </select>

Abnormal results of:

    org.apache.ibatis.binding.BindingException: 
    Parameter 'id' not found. 
    Available parameters are [1, 0, param1, param2]

[Named Parameters: Packaging explicitly specified parameters:

public Employee getEmpByIdAndLastName(@Param("id") Integer id, @Param("lastName") String lastName);

Thus by #{id},#{lastName}extraction of the parameters in this way:

<select id="getEmpByIdAndLastName" resultType="com.atguigu.mybatis.bean.Employee">
        select * from tbl_employee where id = #{id} and last_name=#{lastName}
</select>

What is MyBatis?

MyBatis persistence framework is to support outstanding ordinary SQL queries, stored procedures and advanced mappings. MyBatis eliminates almost all manual settings and parameters JDBC code and retrieve the result set. MyBatis can use simple XML or Annotations for configuration and map primitives, Map interfaces and Java POJO (Plain Old Java Objects, ordinary Java Objects) to database records in.

MyBatis Download: https: //github.com/mybatis/mybatis-3/releases

Mybatis examples

CRUD operations of a User table:

User表:

-- ----------------------------
-- Table structure for `user`
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `userName` varchar(50) DEFAULT NULL,
  `userAge` int(11) DEFAULT NULL,
  `userAddress` varchar(200) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'summer', '30', 'shanghai');
INSERT INTO `user` VALUES ('2', 'test2', '22', 'suzhou');
INSERT INTO `user` VALUES ('3', 'test1', '29', 'some place');
INSERT INTO `user` VALUES ('4', 'lu', '28', 'some place');
INSERT INTO `user` VALUES ('5', 'xiaoxun', '27', 'nanjing');
 

Build a mybatis in the Src directory xml configuration file Configuration.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>
    <!-- mybatis别名定义 -->
    <typeAliases> 
        <typeAlias alias="User" type="com.mybatis.test.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/mybatis" />
            <property name="username" value="root"/>
            <Property name = "password" value = "ADMIN" /> 
            </ the dataSource> 
        </ Environment> 
    </ Environments> 
    
    <-! mapper MyBatis of files, each corresponding to a xml configuration file Interface -> 
    <by mappers> 
        < = Resource Mapper "COM / MyBatis / Test / User.xml" /> 
    </ by mappers> 
</ Configuration>

User mappers defined profile of User.xml

<? xml Version = "1.0" encoding = "UTF-8"?> 
<DOCTYPE Mapper the PUBLIC! "- // mybatis.org//DTD Mapper 3.0 // EN" 
"http://mybatis.org/dtd/mybatis mapper.dtd--3 "> 

<Mapper namespace =" com.mybatis.test.IUserOperation "> 

    <-! SELECT statement -> 
    <SELECT ID =" selectUserByID "the parameterType =" int "= the resultType" the User "> 
        SELECT WHERE user` from the user.id `* # = {ID} 
    </ SELECT> 
    
    <-! defined resultMap, can solve the problem of inconsistency of the class attribute names and database column name -> 
    <-! <the resultMap type =" the User "ID =" userResultMap "> 
        <Property ID =" ID "column =" user_id "/> 
        <= Result Property"userName" column="user_userName"  />
        <result property="userAge" column="user_userAge"  />
        <Property Result = "userAddress" column = "user_userAddress" /> 
    </ resultMap> -> 
    
    <-! return list select statement, attention is directed to the front resultMap value defined -> 
    <-! <select = ID "selectUsersByName" the parameterType = "String" The resultMap = "userResultMap"> 
        SELECT * WHERE User user.username from the userName = # {} 
    </ SELECT> -> 
    
    <SELECT ID = "selectUsersByName" the parameterType = "String" = the resultType "the User"> 
        SELECT * WHERE User user.username from the userName = # {} 
    </ SELECT> 
    
    <-! execute SQL statements increase operation. id and parameterType coincide with addUser method IUserOperation interface names and parameter types. 
    useGeneratedKeys set to "true"
        useGeneratedKeys="true" keyProperty="id"> 
        insert into user(userName,userAge,userAddress)  
             values(#{userName},#{userAge},#{userAddress})  
    </insert>
    
    <update id="updateUser" parameterType="User" >
        update user set userName=#{userName},userAge=#{userAge},userAddress=#{userAddress} where id=#{id}
    </update>
    
    <delete id="deleteUser" parameterType="int">
        delete from user where id=#{id}
    </delete>
    
</mapper>

Profiles achieve the mapping between the interface and SQL statements. selectUsersByName uses two kinds of ways, but also a realization commented, using resultMap can attribute mapping and database column names good relationship is defined, property as a property class, column is a column name of the table, it can also be a table column names alias!

User class definition:

package com.mybatis.test;

public class User {
    
    private int id;
    private String userName;
    private int userAge;
    private String userAddress;
    
    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;
    }
    
    public String getUserAddress() {
        return userAddress;
    }
    
    public void setUserAddress(String userAddress) {
        this.userAddress = userAddress;
    }
    
    @Override
    public String toString(){
        return this.userName+" "+this.userAge+" "+this.userAddress;
    }

}
 

IUserOperaton definition:

 
package com.mybatis.test;

import java.util.List;

public interface IUserOperation {
    
    public User selectUserByID(int id);
    
    public List<User> selectUsersByName(String userName);
    
    public void addUser(User user);
    
    public void updateUser(User user);
    
    public void deleteUser(int id);
    
}
 

IUserOperation operation of the operation corresponding to the id of the interface, and the function name mybatis xml configuration file.

Test class Test:

 
package com.mybatis.test;

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;

public class Test {

    private static SqlSessionFactory sqlSessionFactory;
    private static Reader reader;

    static {
        try {
            reader = Resources.getResourceAsReader("Configuration.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static SqlSessionFactory getSession() {
        return sqlSessionFactory;
    }

    public void getUserByID(int userID) {
        SqlSession session = sqlSessionFactory.openSession();
        try {
            IUserOperation userOperation = session
                    .getMapper(IUserOperation.class);
            User user = userOperation.selectUserByID(userID);
            if (user != null) {
                System.out.println(user.getId() + ":" + user.getUserName()
                        + ":" + user.getUserAddress());
            }

        } finally {
            session.close();
        }
    }

    public void getUserList(String userName) {
        SqlSession session = sqlSessionFactory.openSession();
        try {
            IUserOperation userOperation = session
                    .getMapper(IUserOperation.class);
            List<User> users = userOperation.selectUsersByName(userName);
            for (User user : users) {
                System.out.println(user.getId() + ":" + user.getUserName()
                        + ":" + user.getUserAddress());
            }

        } finally {
            session.close();
        }
    }

    /**
     * 增加后要commit
     */
    public void addUser() {
        User user = new User();
        user.setUserAddress("place");
        user.setUserName("test_add");
        user.setUserAge(30);
        SqlSession session = sqlSessionFactory.openSession();
        try {
            IUserOperation userOperation = session
                    .getMapper(IUserOperation.class);
            userOperation.addUser(user);
            session.commit();
            System.out.println("新增用户ID:" + user.getId());
        } finally {
            session.close();
        }
    }

    /**
     * 修改后要commit
     */
    public void updateUser() {
        SqlSession session = sqlSessionFactory.openSession();
        try {
            IUserOperation userOperation = session
                    .getMapper(IUserOperation.class);
            User user = userOperation.selectUserByID(1);
            if (user != null) {
                user.setUserAddress("A new place");
                userOperation.updateUser(user);
                session.commit();
            }
        } finally {
            session.close();
        }
    }

    /**
     * 删除后要commit.
     * 
     * @param id
     */
    public void deleteUser(int id) {
        SqlSession session = sqlSessionFactory.openSession();
        try {
            IUserOperation userOperation = session
                    .getMapper(IUserOperation.class);
            userOperation.deleteUser(id);
            session.commit();
        } finally {
            session.close();
        }
    }

    public static void main(String[] args) {
        try {
            Test test = new Test();
            // test.getUserByID(1);
            // test.getUserList("test1");
            // test.addUser();
            // test.updateUser();
            // test.deleteUser(6);

        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

}
 

 MyBatis Mapper single parameter, parameter passing plurality of difference parameters

1, a single parameter

mybatis do not treat
# parameter name {/} any name: Remove the parameter value.

In the interface EmployeeMapper.javathere in

public Employee getEmpById(Integer id);

EmployeeMapper.xmlBy #{id}extraction parameter value, because only one, arbitrary names may be as follows:

<select id="getEmpById" resultType="com.atguigu.mybatis.bean.Employee">
         select * from tbl_employee where id = #{abcde}
</select>

2, a plurality of parameters

mybatis will do special treatment

We are the interface EmployeeMapper.javaa new method added:

public Employee getEmpByIdAndLastName(Integer id,String lastName); 

Value Method: The #{id},#{lastName}extraction parameters in this manner

<select id="getEmpByIdAndLastName" resultType="com.atguigu.mybatis.bean.Employee">
        select * from tbl_employee where id = #{id} and last_name=#{lastName}
    </select>

Abnormal results of:

    org.apache.ibatis.binding.BindingException: 
    Parameter 'id' not found. 
    Available parameters are [1, 0, param1, param2]

[Named Parameters: Packaging explicitly specified parameters:

public Employee getEmpByIdAndLastName(@Param("id") Integer id, @Param("lastName") String lastName);

Thus by #{id},#{lastName}extraction of the parameters in this way:

<select id="getEmpByIdAndLastName" resultType="com.atguigu.mybatis.bean.Employee">
        select * from tbl_employee where id = #{id} and last_name=#{lastName}
</select>

Guess you like

Origin www.cnblogs.com/F017/p/11605803.html