表格的单查和修改

  1. 创建连接测试数据库

#部门表
drop table if exists dept;
create table dept(
    did int primary key,
    dname varchar(20),
    dinfo varchar(50)
);

insert into dept values(101,'市场部','负责公司市场的开拓');
insert into dept values(102,'产品部','负责公司产品的营销');
insert into dept values(103,'研发部','负责公司产品的研发');
insert into dept values(104,'测试部','负责公司产品的测试');

select * from dept;
  1. 创建Java项目并导入mybatis框架的jar包

表格的单查和修改_第1张图片
  1. 创建和表和实体类

package com.e.bean;

public class Dept {
    private Integer did;
    private String dname;
    private String dinfo;

    public Integer getDid() {
        return did;
    }

    public void setDid(Integer did) {
        this.did = did;
    }

    public String getDname() {
        return dname;
    }

    public void setDname(String dname) {
        this.dname = dname;
    }

    public String getDinfo() {
        return dinfo;
    }

    public void setDinfo(String dinfo) {
        this.dinfo = dinfo;
    }

    @Override
    public String toString() {
        return "Dept{" +
                "did=" + did +
                ", dname='" + dname + '\'' +
                ", dinfo='" + dinfo + '\'' +
                '}';
    }
}

创建接口 单查

package com.q.dao;

import com.q.bean.Dept;

public interface DeptDao {
    Dept selectByDid(int did);
}

mapper映射配置文件




    

框架的核心配置文件




    
    
        
    
    
        
    
    
        
            
            
                
                
                
                
            
        
    
    
        
    
    
    
    

进行测试

package com.q.test;

import com.q.bean.Dept;
import com.q.dao.DeptDao;
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.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;

public class DeptTest {
    InputStream stream=null;
    SqlSessionFactoryBuilder builder=null;
    SqlSessionFactory factory=null;
    SqlSession sqlSession=null;
    DeptDao deptDao=null;
    @Before
    public void init() throws IOException {
        stream= Resources.getResourceAsStream("mybatis.xml");
        builder=new SqlSessionFactoryBuilder();
        factory=builder.build(stream);
        sqlSession=factory.openSession();
        deptDao=sqlSession.getMapper(DeptDao.class);
    }
    @Test
    public void testSelectByDid(){
        Dept dept=deptDao.selectByDid(101);
        System.out.println(dept);
    }
    @After
    public void distroy() throws IOException {
        sqlSession.commit();
        sqlSession.close();
        stream.close();
    }
}

你可能感兴趣的:(mybatis,数据库,mysql)