Mybatis entry notes (2) - Implementing CRUD agent-based Dao

Mapper interface development method requires the programmer to write Mapper interface (an interface corresponding to Dao), created by the dynamic proxy object interface Mybatis frame according to the interface definition, the same method of the top member of the proxy object class methods Dao interface.

Directory Structure:

XML way

Creating steps:

  1. Create a maven project, nothing at all on ok, and import coordinates;

  2. Dao write User entity classes and interfaces.

    Creating com.ben.domain package java directory, create a User entity class

    Creating com.ben.dao package, create IUserDao interfaces (can also be written UserDao or UserMapper)

    public interface IUserDao {
        // 通过ID查询一个用户
        User findUserById(Integer id);
        // 根据用户名模糊查询用户列表
        List<User> findUserByUsername(String userName);
        // 添加用户
        int insertUser(User user);
        // 更新用户
        void updateUserById(User user);
        // 删除用户
        void deleteUserById(Integer id);
    }
  3. In the resources folder, create a master configuration file SqlMapConfig.xml Mybatis of;

  4. Import log4j.properties file in the resources folder

  5. Creating the resources in the package com-> ben-> dao, create a mapping profile IUserDao.xml;

    Claim:

    Create positions: persistence layer interfaces must be on the same package;

    Name: the file name must be named to the persistence layer interface name, extension is .xml Example: Note: namespace configuration files must be durable layer interface full class name



  6. Create a test class com.ben.test.MybatisTest in java, 6-step;

1.读取配置文件
in = Resources.getResourceAsStream("SqlMapConfig.xml");
2.创建SqlSessionFactory工厂
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
3.创建SqlSession工厂对象
SqlSessionFactory factory = builder.build(in);
4.使用工厂生产SqlSession对象
session = factory.openSession();
5.创建Dao接口的代理对象
userdao = session.getMapper(IUserDao.class);
6.执行操作:增删改查等操作
7.释放资源
session.commit();
session.close();
in.close();
/**
 * @ClassName: MybatisTest
 * @author: benjamin
 * @version: 1.0
 * @description: TODO
 * @createTime: 2019/07/07/21:54
 */

public class MybatisTest {

    private SqlSessionFactory factory;
    private IUserDao userdao;
    private InputStream in;
    private SqlSession session;

    // 作用:在测试方法前执行这个方法
    @Before
    public void setUp() throws Exception {
        //1.读取配置文件
        in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //2.创建SqlSessionFactory工厂
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        //3.创建SqlSession工厂对象
        SqlSessionFactory factory = builder.build(in);
        //4.使用工厂生产SqlSession对象
        session = factory.openSession();
        //5.创建Dao接口的代理对象
        userdao = session.getMapper(IUserDao.class);
    }

    @After//在测试方法执行完成之后执行
    public void destroy() throws IOException {
        session.commit();
        session.close();
        in.close();
    }


    //通过Id查询一个用户
    @Test
    public void testFindUserById() {
        //5.使用代理对象执行方法
        User user = userdao.findUserById(1);
        System.out.println(user);
    }

    //根据用户名模糊查询用户列表
    @Test
    public void testFindUserByUserName() {
        List<User> list = userdao.findUserByUsername("王");
        for (User user : list) {
            System.out.println(user);
        }
    }

    //添加用户
    @Test
    public void testInsertUser() throws IOException {
        User user = new User();
        user.setUsername("大王");
        user.setBirthday(new Date());
        user.setAddress("sadfsafsafs");
        user.setSex("2");
        int i = userdao.insertUser(user);
        System.out.println("插入id:" + user.getId());//插入id:35
    }

    //更新用户
    @Test
    public void testUpdateUserById() throws IOException {
        User user = new User();
        user.setId(35);
        user.setUsername("一一");
        user.setBirthday(new Date());
        user.setAddress("西安市");
        user.setSex("1");
        userdao.updateUserById(user);

        System.out.println(user.getId());
    }

    //删除用户
    @Test
    public void testDeleteUserById() throws IOException {
        userdao.deleteUserById(29);
    }
}

Precautions:

  1. Mybatis it in the name of the persistence layer user interface is also known as: Mapper. So: IUserDao and IUserMapper is the same.

  2. Create a directory in the idea of ​​time, and it is not the same package. When you create a package package: com.ben.dao it is the tertiary structure; when the directory listings created: com.ben.dao is a directory.

  3. Mapping configuration file of mapper IUserDao.xml tag configuration:

    namespace: fully qualified class name dao interface. For example com.ben.dao.IUserDao

    id: Mapper Interface (IUserDao) interface method name;

    parameterType: Incoming parameter type interface method;

    resultType:接口方法的返回值类型;

遵从了第3点,在开发中就无须再写dao的实现类。mybatis 为我们实现,即为动态代理dao实现。

注解方式

  1. IUserDao.xml移除;

  2. dao接口(IUserDao)的方法上使用@Select注解,并且指定SQL语句;

    public interface IUserDao {
        //用户的持久层操作,查询所有操作。
        @Select("select * from user")
        List<User> findAll();
    }
  3. SqlMapConfig.xml中的mapper配置时,使用class属性指定dao接口的全限定类名。

<mappers>
  <mapper class="com.ben.dao.IUserDao"/>
</mappers>

编写测试类

/**
 * @ClassName: MybatisTest
 * @author: benjamin
 * @version: 1.0
 * @description: TODO
 * @createTime: 2019/07/07/21:54
 */

public class MybatisTest {

    private SqlSessionFactory factory;
    private IUserDao userdao;
    private InputStream in;
    private SqlSession session;

    // 作用:在测试方法前执行这个方法
    @Before
    public void setUp() throws Exception {
        //1.读取配置文件
        in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //2.创建SqlSessionFactory工厂
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        //3.创建SqlSession工厂对象
        SqlSessionFactory factory = builder.build(in);
        //4.使用工厂生产SqlSession对象
        session = factory.openSession();
        //5.创建Dao接口的代理对象
        userdao = session.getMapper(IUserDao.class);
    }

    @After//在测试方法执行完成之后执行
    public void destroy() throws IOException {
        session.commit();
        session.close();
        in.close();
    }

    //查询所有用户
    @Test
    public void findAll(){
        List<User> list = userdao.findAll();
        for (User user : list) {
            System.out.println(user);
        }
    }
}

Guess you like

Origin www.cnblogs.com/benjieqiang/p/11204155.html