MyBatis - Crude

I'm all you paranoid and greedy, came from my love for you twenty-four hours full to the brim.

1、namespace

Package name to the namespace and Dao / mapper interface is consistent package name

2、select

Select query

  • id: is the method name in the corresponding namespace
  • resultType: Returns the value of SQL statements executed
  • parameterType: Parameter Type
  1. Write Interface

    package com.rui.dao;
    
    import com.rui.pojo.User;
    
    import java.util.List;
    
    public interface UserMapper {
        //根据id查询用户
        User getUserById(int id);
    }
  2. Corresponding write mapper sql statement

    <select id="getUserById" resultType="com.rui.pojo.User" parameterType="int">
        /*定义sql*/
        select * from mybatis.user where id = #{id};
    </select>
  3. test

    @Test
    public void getUserById(){
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.getUserById(1);
        System.out.println(user);
        sqlSession.close();
    }

3、Insert

4、Update

5、Delete

6, error analysis

  • Labels do not match error
  • resource binding mapper, need to use the path
  • Configuration file must meet specifications
  • NullPointException, is not registered with resources
  • Chinese garbage problem in the xml file output
  • maven resource does not export issues

7, Universal Map

Assuming that too much of our entity class, or database tables, fields or parameters, we should consider using the Map

//万能Map
int addUser2(Map<String,Object> map);
<!--对象中的属性,可以直接取出来 parameterType=传递map中的key-->
<insert id="addUser2" parameterType="map">
    insert into mybatis.user (id, name, pwd) values (#{userId},#{userName},#{password});
</insert>
//万能map
@Test
public void addUser2(){
    SqlSession sqlSession = MyBatisUtils.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    HashMap<String, Object> map = new HashMap<>();
    map.put("userId",4);
    map.put("userName","王五");
    map.put("password","23333");
    mapper.addUser2(map);
    //提交事务
    sqlSession.commit();
    sqlSession.close();
}

Map transmission parameters, taken directly to key in the sql. [ParameterType = "map"]

Objects are passed parameters, take the objects directly sql attribute. [ParameterType = "Object"]

Only a case where the basic type parameter, can be directly taken to the sql

Multiple parameters Map, or notes

8, fuzzy query

  1. Java code is executed when the transfer wildcard %%

    List<User> userList=mapper.getUserLike("%李%");
  2. Use wildcards in sql mosaic

    select * from mybatis.user where name like "%"#{value}"%"

Guess you like

Origin www.cnblogs.com/huangdajie/p/12438990.html