10 mybatis原始dao的实现方式

本文将阐述mybatis中原始dao方式的实现。

1、环境约束

  • win10 64位操作系统
  • idea2018.1.5
  • jdk-8u162-windows-x64
  • mybatis3.2.8
  • mysql 6.5

2、前提约束

  • 完成idea中创建mybatis项目 https://www.jianshu.com/p/86db0901156f
    请读者注意自己数据库账号密码驱动和url的适配。

3、操作步骤

  • 创建一个t_user
create table t_user(id int,name varchar(20));
insert into t_user(id,name) values(1,'ali');
insert into t_user(id,name) values(2,'xiaoli');
insert into t_user(id,name) values(3,'zhangli');
  • 在src/main/java中创建net.wanho.User.java:
public class User{
  private int id;
  private String name;
  ...
}
  • 在src/main/java中创建net.wanho.UserDao.java:
import net.wanho.User;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface UserDao {
    @Select("select * from t_user")
    List query();
}
  • 在src/main/java中创建net.wanho.UserDaoImpl.java:
import net.wanho.User;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

public class UserDaoImpl implements UserDao {

    private SqlSessionFactory sqlsessionFactory;

    public UserDaoImpl(SqlSessionFactory sqlsessionFactory) {
        this.sqlsessionFactory = sqlsessionFactory;
    }

    @Override
    public List query() {
        SqlSession sqlSession = sqlsessionFactory.openSession();
        List list = sqlSession.selectList("query");
        sqlSession.close();
        return list;
    }
}

  • 在src/java/resources下创建mybatis-config.xml



    
        
            
            
                
                
                
                
            
        
    
    
        
    

  • 在src/main/java文件夹下创建Test.java
import net.wanho.entity.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;
import java.util.List;

public class Test {
    public static void main(String[] args) throws Exception{
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
                .build(inputStream);
        UserDao userDao = new UserDaoImpl(sqlSessionFactory);
        List list = userDao.query();
        System.out.println(list);
    }
}

以上就是mybatis中原始dao的实现方式,用的较少,了解即可。

你可能感兴趣的:(10 mybatis原始dao的实现方式)