欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Mybatis—⑤使用注解开发

程序员文章站 2022-07-08 14:44:43
...

优化项目

事务优化:自动提交事务

//获得一个带事务自动提交功能的SqlSession公共的方法
public static SqlSession getSession(){
		return sqlSessionFactory.openSession(true);
		}

别名优化:pojo包下类自动设置别名

<!--配置别名-->
<typeAliases>
    <!--<typeAlias type="com.kuang.pojo.User" alias="User"/>-->
    <package name="com.kuang.pojo"/>
</typeAliases>

mapper映射文件路径修改

<mappers>
    <!--class对应的是一个接口类-->
    <!--resource对应的是一个接口类的映射文件-->
    <mapper class="com.kuang.dao.UserDao"/>
</mappers>

我们来看一种更有效的优化项目的方法

使用注解进行开发

CRUD的注解:
●@insert()
●@delete()
●@update()
●@select()

1、UserDao

package com.an.dao;

import com.an.pojo.User;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;
import java.util.Map;

public interface UserDao {
    //获取全部用户
    @Select("select * from user")
    List<User> selectUser();
    //根据ID查找用户
    @Select("select * from user where id = #{id}")
    User selectUserById(int id);
    //添加一个用户
    @Insert("insert into user (id,name,pwd) values (#{id},#{name},#{pwd})")
    int addUser(User user);
    //删除用户
    @Delete("delete from user where id = #{id}")
    int deleteUserById(int id);
    //修改用户
    @Update("update user set name = #{name},pwd = #{pwd} where id = #{id}")
    int updateUser(User user);
    //查询全部用户并分页
    @Select("select * from user limit #{startIndex},#{pageSize}")
    List<User> selectUserLimit(Map<String,Integer> map);
}

2、mybatis核心文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <properties resource="database.properties"/>
    <settings>
        <setting name="logImpl" value="LOG4J"/>
    </settings>

    <!--为一个包里所有类取别名为类名,注意位置为固定的-->
    <typeAliases>
        <package name="com.an.pojo"/>
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/an/dao/UserMapper.xml"/>
    </mappers>
</configuration>

3、工具类

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <properties resource="database.properties"/>
    <settings>
        <setting name="logImpl" value="LOG4J"/>
    </settings>

    <!--为一个包里所有类取别名为类名,注意位置为固定的-->
    <typeAliases>
        <package name="com.an.pojo"/>
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/an/dao/UserMapper.xml"/>
    </mappers>
</configuration>

4、测试

package com.an.dao;

import com.an.pojo.User;
import com.an.utils.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.Test;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserMapperTest {
    @Test
    public void selectUser(){
        SqlSessionFactory sqlSessionFactory = MyBatisUtils.getSqlSessionFactory();
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        List<User> users = mapper.selectUser();
        for (User user : users) {
            System.out.println(user);
        }
        sqlSession.close();
    }
    @Test
    public void selectUserById(){
        SqlSessionFactory sqlSessionFactory = MyBatisUtils.getSqlSessionFactory();
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        User user = mapper.selectUserById(1);
        System.out.println(user);
        sqlSession.close();
    }
    @Test
    public void addUser(){
        SqlSessionFactory sqlSessionFactory = MyBatisUtils.getSqlSessionFactory();
        SqlSession sqlSession = sqlSessionFactory.openSession();

        User user = new User(7,"anye","123456");
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        int i = mapper.addUser(user);
        sqlSession.commit();//关闭sqlSession
        if(i>0){
            System.out.println("插入成功!");
        }
    }
    @Test
    public void deleteUserById(){
        SqlSessionFactory factory = MyBatisUtils.getSqlSessionFactory();
        SqlSession sqlSession = factory.openSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        int i = mapper.deleteUserById(7);
        if(i>0){
            System.out.println("删除成功");
        }
        sqlSession.close();
    }
    @Test
    public void updateUser(){
        SqlSessionFactory sqlSessionFactory = MyBatisUtils.getSqlSessionFactory();
        SqlSession sqlSession = sqlSessionFactory.openSession();
        User user = new User(1, "anye", "anyebaobao");
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        int i = mapper.updateUser(user);
        if(i>0){
            System.out.println("修改成功");
        }
        sqlSession.close();
    }
    @Test
    public void selectUserLimit(){
        SqlSessionFactory factory = MyBatisUtils.getSqlSessionFactory();
        SqlSession sqlSession = factory.openSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        int currentPage = 2;//当前在第2页
        int pageSize = 3;//每页有3条数据
        Map<String, Integer> map = new HashMap<String, Integer>();
        map.put("startIndex",(currentPage-1)*pageSize);
        map.put("pageSize",pageSize);
        List<User> users = mapper.selectUserLimit(map);
        for (User user : users) {
            System.out.println(user);
        }
    }
}