栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

第一个Mybatis程序

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

第一个Mybatis程序

第一个Mybatis程序
  1. 新建数据库和表
CREATE DATAbase `mybatis`;

USE `mybatis`;

CREATE TABLE `user`(
	`id` INT(20) NOT NULL PRIMARY key,
	`name` VARCHAR(30) DEFAULT NULL,
	`pwd` VARCHAR(30) DEFAULT NULL
)ENGINE=INNODB DEFAULT CHARSET=utf8;

INSERT INTO `user` (id,name,pwd) 
VALUES (1,'mm1','mm1pwd'),
(2,'mm2','mm1pwd'),
(3,'mm3','mm1pwd');
  1. 新建一个maven项目
  2. 删除src
  3. 导入依赖
    

        
        
            mysql
            mysql-connector-java
            8.0.23
        
        
        
        
            org.mybatis
            mybatis
            3.4.6
        
        
        
        
            junit
            junit
            4.12
            test
        
    

5.mybatis核心配置文件





    
        
            
            
                
                
                
                
            
        
    

  1. 编写mybatis工具类
// sqlSessionFactory
public class MybatisUtil {
    private static SqlSessionFactory sqlSessionFactory = null;

    static{
        try {
            String resource = "org/mybatis/example/mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }
}

7.编写pojo类

public class User implements Serializable {
    private Integer id;
    private String name;
    private String pwd;
    }

8编写dao接口

public interface UserDao {
    List getUserList();
}

9.编写UserDao.xml





    
        select * from mybatis.user
    

10.在核心配置文件中注册mapper

    
        
    

11.编写测试类

    @Test
    public void test(){
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        List userList = userDao.getUserList();
        System.out.println(userList.toString());
        sqlSession.close();
    }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/531492.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号