MyBatis-maven-User例子-根據id查詢User

weixin_33727510發表於2018-08-28
public interface SqlSession extends Closeable {

  /**
   * Retrieve a single row mapped from the statement key
   * @param <T> the returned object type
   * @param statement
   * @return Mapped object
   */
  <T> T selectOne(String statement);

  /**
   * Retrieve a single row mapped from the statement key and parameter.
   * @param <T> the returned object type
   * @param statement Unique identifier matching the statement to use.
   * @param parameter A parameter object to pass to the statement.
   * @return Mapped object
   */
  <T> T selectOne(String statement, Object parameter);
}
<select id="findOne" resultType="pojo.User">
    select * from user where id=1;
    </select>
    //根據id查詢記錄
    @Test
    public void findOne(){
        // 2.建立sqlsession物件,執行sql
        SqlSession session = ssf.openSession();
        User user = session.selectOne("userns.findOne");
        System.out.println(user);
        // 4.釋放資源
        session.close();
    }

等價查詢,這種方式更靈活

<!--根據id查詢記錄-->
<select id="findOne" parameterType="int" resultType="pojo.User">
select * from user where id=#{id};
</select>
    //根據id查詢記錄
    @Test
    public void findOne(){
        // 2.建立sqlsession物件,執行sql
        SqlSession session = ssf.openSession();
        User user = session.selectOne("userns.findOne",1);
        System.out.println(user);
        // 4.釋放資源
        session.close();
    }

相關文章