MyBatis学习总结[1]-入门

文档地址http://www.mybatis.org/mybatis-3/zh/index.html

安装

要使用 MyBatis, 只需将 mybatis-x.x.x.jar 文件置于 classpath 中即可。还要放所使用的数据库的驱动。
MyBatis学习总结[1]-入门_第1张图片

配置文件



<configuration> 

   
   <typeAliases>
      <package name="me.model"/>
  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://localhost:3306/mybatis"/>
        <property name="username" value="root"/>
        <property name="password" value="1234"/>
      dataSource>
    environment>   
  environments>

  <mappers>
    
    <mapper resource="me/mapper/UserMapper.xml"/>
    
  mappers>
configuration>

实体类

package me.model;

import java.util.List;

public class User {
    private int id;
    private String name;
    private String age;

    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;
    }
    public String getAge() {
        return age;
    }
    public void setAge(String age) {
        this.age = age;
    }
    @Override
    public String toString() {
        // TODO Auto-generated method stub
        return id+" "+name+" "+age+" ";
    }
}

Usermapper.xml



<mapper namespace="me.dao.UserDao">
  <select id="selectById" parameterType="int" resultType="User">
    select * from users where id = #{id}
  select>
mapper>

Service类

package me.service;

import java.io.InputStream;
import java.util.List;
import me.model.User;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class UserService {
//从 XML 中构建 SqlSessionFactory
    String resource = "conf.xml";
    InputStream is = UserService.class.getClassLoader().getResourceAsStream(
            resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
            .build(is);
    SqlSession session = sqlSessionFactory.openSession();
    public void selectUserById(int id) {
    //me.dao.UerDao.selectById为map文件的xml,namespace+select标签id
        User user=session.selectOne("me.dao.UerDao.selectById",id);
    }

    public void close(){
        session.close();
    }
}

测试类

package me.service;

import static org.junit.Assert.*;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
public class UserServiceTest {
    static UserService s=null;
    @BeforeClass
    public static void before(){
        s=new UserService();
    }
    @Test
    public void test() {
        s.selectUserById(2);
    }

    @AfterClass
    public static void after(){
        s.close();
    }

}

结果

MyBatis学习总结[1]-入门_第2张图片

语句执行成功,另外这个日志是log4j输出的,配置方法点这里

你可能感兴趣的:(框架)