MyBatis02

学习了3种使用方式

案例链接(包含jar包): https://pan.baidu.com/s/1hykf9d2IEFoEPl8XlMWaqQ 提取码: m342

方式二:

通过dao层去调用xml中的方法,跟方式一类似

步骤1:配置SqlMapConfig.xml和Car.xml文件,和方式一完全一样,还有在com.hello.pojo下新建Car类

步骤2:新建com.hello.dao包并在里面新建一个CarDao接口和实现类CarDaoImpl

CarDao接口中有一些需要用到的增删改查的未实现方法,比如

package com.hello.dao;

import java.util.List;

import com.hello.pojo.Car;

public interface CarDao {

// 根据 id 查车

public Car findCarById(Integer id);

// 根据 name 模糊查询

public List findCarByName(String name);

}

实现类CarDaoImpl中上面那些方法的实现,说是实现其实并不需要我们去做增删改查的操作,因为我们已经在Car.xml里面做好了这些操作,所以在CarDaoImpl中我们只需要调用Car.xml中的方法即可。

package com.hello.dao;

import java.util.List;

import org.apache.ibatis.session.SqlSession;

import org.apache.ibatis.session.SqlSessionFactory;

import com.hello.dao.CarDao;

import com.hello.pojo.Car;

public class CarDaoImpl implements CarDao {

private SqlSessionFactory factory;

public CarDaoImpl() {

super();

}

public CarDaoImpl(SqlSessionFactory factory) {

super();

this.factory = factory;

}

@Override

public Car findCarById(Integer id) {

// 获取 SqlSession

SqlSession session = factory.openSession();

return session.selectOne("aa.findCarById", id);

}

@Override

public List findCarByName(String name) {

// 获取 SqlSession

SqlSession session = factory.openSession();

return session.selectList("aa.findCarByName", name);

}

}

其中,里面的factory对象需要我们在测试类那边调用构造方法传过来,具体测试类怎么实现,看下面

步骤3:创建测试类CarTest

package com.hello.test;

import java.io.IOException;

import java.io.InputStream;

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 com.hello.dao.CarDaoImpl;

import com.hello.pojo.Car;

public class CarTest {

private SqlSessionFactory factory;

// @Before 注解,会在 @Test 注解之前执行

@Before

public void getFactory() throws IOException {

// 1. 加载核心配置文件

InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");

// 2. 获取 SqlSessionFactory

SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();

factory = builder.build(is);

}

@Test

public void findCarById() throws Exception {

CarDaoImpl cdao = new CarDaoImpl(factory);

Car car = cdao.findCarById(1);

System.out.println("我找到的车:" + car);

}

}

执行测试方法findCarById(),因为 getFactory() 前加了注解@Before,所以会在执行findCarById()方法之前执行,也就得到了factory对象,通过new CarDaoImpl(factory)把factory对象传过去,CarDaoImpl类中也就得到了factory对象。

你可能感兴趣的:(MyBatis02)