1 - 搭建环境

一.单独使用Mybaits

项目结构图--基于maven

jar包
测试:junit
数据库驱动: mysql-connector-java
Mybatis: mybatis
log4j: log4j-core log4j-api
1.创建db,properties

database.driver=com.mysql.jdbc.Driver
database.url=jdbc:mysql://localhost:3306/dbName?serverTimezone=UTC 
database.username=root
database.password=***

2.配置mybatis.xml




    
    
    
    
        
        
    
    
    
        
        
    
    
    
        
            
            
                
                
                
                
            
        
    
    
    
        
    

3.日志



    
        
            
        
    

    
        
        
        
        
            
        
    

4.dao和model

package dao;

import model.Student;

import java.util.List;

public interface StudentMapper {
    List selectAllStudent();
}


package model;

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

    public Student() {
    }

    public Student(String name, int age) {
        this.name = name;
        this.age = 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 int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

5.mapple





    

6.测试

import dao.StudentMapper;
import model.Student;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;

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

public class AppTest {

    SqlSessionFactory factory = null;

    @Before
    public void prepare() throws IOException{
        InputStream inputStream = Resources.getResourceAsStream("mybatis.xml");
        factory = new SqlSessionFactoryBuilder().build(inputStream);
        inputStream.close();
    }

    @Test
    public void test(){

        SqlSession session=  factory.openSession();
        try{
            StudentMapper studentMapper = session.getMapper(StudentMapper.class);

            List list = studentMapper.selectAllStudent();
            Iterator iterator = list.iterator();
            while(iterator.hasNext()){
                Student student = iterator.next();
                System.out.println(student);
            }
        }finally{
            session.commit();
            session.close();
        }
    }
}

你可能感兴趣的:(1 - 搭建环境)