Mybatis---框架搭建---增删查改

下载依赖网址
https://search.maven.org/

pom.xml




  4.0.0

  cn.kgc
  mybatis-demo
  1.0-SNAPSHOT

  mybatis-demo
  
  http://www.example.com

  
    UTF-8
    1.7
    1.7
  

  
    
      junit
      junit
      4.11
      test
    

    
      org.mybatis
      mybatis
      3.5.2
    

    
      mysql
      mysql-connector-java
      8.0.17
    

    
      org.projectlombok
      lombok
      1.18.8
    
	
      log4j
      log4j
      1.2.17
      test
    

  

  
    
      
        
          maven-clean-plugin
          3.1.0
        
        
          maven-resources-plugin
          3.0.2
        
        
          maven-compiler-plugin
          3.8.0
        
        
          maven-surefire-plugin
          2.22.1
        
        
          maven-jar-plugin
          3.0.2
        
        
          maven-install-plugin
          2.5.2
        
        
          maven-deploy-plugin
          2.8.2
        
        
          maven-site-plugin
          3.7.1
        
        
          maven-project-info-reports-plugin
          3.0.0
        
      
    
  


main目录下新建resources目录,resources目录下新建mappers目录
mappers目录下
UserMapper.xml(映射文件,写sql语句的地方)





    
    
    
    
    
        INSERT INTO smbms_user(userCode,userName,userPassword)VALUES(#{userCode},#{userName},#{userPassword})
    
    
        update smbms_user set userCode = #{userCode},userName = #{userName},userPassword = #{userPassword} where id = #{id}
    
    
        delete from smbms_user where id=#{id}
    




    
    

    
    



    
        
        
        
        
    
    



    
        
        
        
        
        

        
            
            
            
        
    
    


    
        
        
        
        
        

        
    
    
        
        
        
    
    


    
        
        
            
        
    
    



    
    
        
        
            
        
    
    

    
    
        update smbms_user
        
            userCode = #{userCode},
            userName = #{userName},
            userPassword = #{userPassword},
        
        where id = #{id}

    


    
        
    
    


    




main根目录下
db.properties

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/smbms?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai&useSSL=false
username=root
password=123456

log4j.properties

log4j.rootLogger=DEBUG,CONSOLE,file
#log4j.rootLogger=ERROR,ROLLING_FILE
log4j.logger.cn.kgc.dao=debug
log4j.logger.com.ibatis=debug
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=debug
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=debug
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=debug
log4j.logger.java.sql.Connection=debug
log4j.logger.java.sql.Statement=debug
log4j.logger.java.sql.PreparedStatement=debug
log4j.logger.java.sql.ResultSet=debug
log4j.logger.org.tuckey.web.filters.urlrewrite.UrlRewriteFilter=debug

######################################################################################
# Console Appender  \u65e5\u5fd7\u5728\u63a7\u5236\u8f93\u51fa\u914d\u7f6e
######################################################################################
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.Threshold=error
log4j.appender.CONSOLE.Target=System.out
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern= [%p] %d %c - %m%n


######################################################################################
# DailyRolling File  \u6bcf\u5929\u4ea7\u751f\u4e00\u4e2a\u65e5\u5fd7\u6587\u4ef6\uff0c\u6587\u4ef6\u540d\u683c\u5f0f:log2009-09-11
######################################################################################
log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.DatePattern=yyyy-MM-dd
log4j.appender.file.File=log.log
log4j.appender.file.Append=true
log4j.appender.file.Threshold=error
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-M-d HH:mm:ss}%x[%5p](%F:%L) %m%n


log4j.logger.com.opensymphony.xwork2=error

mybatis-config.xml





    
        
    
        
    
    
    
        
    

    
        
            
            
                
                
                
                
            

        
        
            
            
        
    
    
    
        
    


pojo目录下的类加入(setting–plugins需导入lombok)
@Data
@AllArgsConstructor
@NoArgsConstructor

dao目录下
UserMapper接口

package cn.kgc.dao;
import cn.kgc.pojo.Bill;
import cn.kgc.pojo.Provider;
import cn.kgc.pojo.User;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;

public interface UserMapper {
    //查询
    List getUserList();
    //根据id查询User对象
    User findById(int id);
    //根据姓名  模糊查询
    List findByName(String userName);
    //增加
    int insert(@Param(value = "userCode")String userCode,@Param(value = "userName")String userName,@Param(value = "userPassword")String userPassword);
    //修改
    int update(@Param(value = "userCode")String userCode,@Param(value = "userName")String userName,@Param(value = "userPassword")String userPassword,@Param(value = "id")long id);
    //增加
    int delete(long id);


    //查询   对象入参
    List getUserListByUser(User user);
    //查询   Map入参
    List getUserListByMap(Map userMap);


    //查询
    List getUserList2();
    //association  一对一
    User getUserByRoleId(Integer userRole);
    //collection  一对多
    ListgetUserListByRoleId(Integer userRole);

    //模糊查询 根据id  一对多查询
    List findBillByProName(String ProName);
    //模糊查询 根据id  一对多查询   if-trim判断参数
    List findBillByProName2(@Param(value = "productName")String productName,@Param(value = "providerId")int providerId);
    //修改   set---if 判断参数
    int update2(User user);
    //foreach  集合入参
    ListfindListByRoleId_foreach_list(List userRoleList);

    //分页显示
//    int count();
    ListgetUserListFen(@Param("from")Integer currentPageNo,
                          @Param("pageSize")Integer pageSize,
                          @Param("userName")String userName,
                          @Param("userRole")Integer userRole
                          );
}


until目录下
MybatisUtil (java文件)

package cn.kgc.until;

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 java.io.IOException;
import java.io.InputStream;

public class MybatisUtil {
    private static SqlSessionFactory sqlSessionFactory;
    // 静态代码块,sqlSessionFactory只创建一次
    static {
        try {
            InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
//    创建sqlSession    false:关闭自动提交。需手动提交
    public static SqlSession createSqlSession(){
        return sqlSessionFactory.openSession(true);
    }
//关闭sqlSession
    public static void closeSqlSession(SqlSession sqlSession){
        if (null != sqlSession){
            sqlSession.close();
        }
    }
}

测试类

package cn.kgc;

import cn.kgc.dao.UserMapper;
import cn.kgc.pojo.Bill;
import cn.kgc.pojo.Provider;
import cn.kgc.pojo.Role;
import cn.kgc.pojo.User;
import cn.kgc.until.MybatisUtil;

import jdk.nashorn.internal.objects.annotations.Constructor;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.apache.ibatis.annotations.ConstructorArgs;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

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

import static org.junit.Assert.assertTrue;

public class AppTest {
    private  static Logger logger=Logger.getLogger(AppTest.class);
    private SqlSession sqlSession;
    private UserMapper mapper;

    @Test
    public void shouldAnswerWithTrue()
    {
        assertTrue( true );
    }
    @Before
    public void init(){
        sqlSession = MybatisUtil.createSqlSession();
        mapper = sqlSession.getMapper(UserMapper.class);
    }
    @After
    public void closeSqlSession(){
        MybatisUtil.closeSqlSession(sqlSession);
    }

    @Test
    public void getUserListTest(){
        //查询
        List userList = mapper.getUserList();
        for (User user:userList) {
            System.out.println("===="+user.toString());
        }
    }
    @Test
    public void findById(){
        //根据id查询
        User byId = mapper.findById(11);
        System.out.println("测试========"+byId);
    }
    @Test
    public void findByName(){
        //根据姓名模糊查询
        List list = mapper.findByName("少");
        for (User user:list) {
            System.out.println("===="+user.toString());
        }
    }
    @Test
    public void add(){
        //增加
        int j = mapper.insert("123", "少爷", "123");
        System.out.println("j============"+j);
    }
    @Test
    public void update(){
        //修改
        int i = mapper.update("456", "少爷", "456", 16);
        System.out.println("i=============="+i);
    }
    @Test
    public void delete(){
        //删除
        int i = mapper.delete(16);
        System.out.println("i=============="+i);
    }

    @Test
    public void getUserListByUser(){
        //查询   对象入参
        User user=new User();
        user.setUserName("赵");
        List list = mapper.getUserListByUser(user);
        for (User user2:list) {
            System.out.println("===="+user2.toString());
        }
    }
    @Test
    public void getUserListByMap(){
        //查询   Map入参
        Map userMap=new HashMap();
        userMap.put("uName","赵");

        List list = mapper.getUserListByMap(userMap);
        for (User user:list) {
            System.out.println("===="+user.toString());
        }
    }
    @Test
    public void getUserList2Test(){
        //查询
        List userList = mapper.getUserList2();
        for (User user:userList) {
            System.out.println("===="+user.toString());
        }
    }
    @Test
    public void getUserListByRoled(){
        //查询   association  一对一
        User userListByRoled = mapper.getUserByRoleId(1);
        System.out.println("===="+userListByRoled);
    }
    @Test
    public void getUserListByRoleId(){
        //查询   collection  一对多
        List userListByRoleId = mapper.getUserListByRoleId(2);
        for(User user:userListByRoleId){
            for(Role role:user.getList()){
                System.out.println("===="+user.getUserName()+"  "+role.getRoleName());
            }
        }
    }
    @Test
    public void findBillByProName2(){
        //模糊查询 根据id  查询
        List billList = mapper.findBillByProName2("大",3);

        System.out.println("订单编码"+"  "+"商品名称"+"  "+"供应商编码"+"  "+"供应商名称"+"  "+"供应商联系人"+"  "+"联系电话"+"  "+"订单金额"+"  "+"是否付款");
        for(Bill bill:billList){
            for(Provider provider:bill.getListProvider()){
                System.out.println(bill.getBillCode()+bill.getProductName()+provider.getProCode()+provider.getProName()+provider.getProContact()+provider.getProPhone()+bill.getTotalPrice()+bill.getIsPayment());
            }
        }
    }
    @Test
    public void update2(){
        //修改
        User user=new User();
        user.setId(14);
        user.setUserName("公子");
        user.setUserPassword("789");
        int i = mapper.update2(user);
        System.out.println("i=============="+i);
    }
    @Test
    public void findListByRoleId(){
        //foreach  集合入参
        Listlist=new ArrayList<>();
        ListroleList=new ArrayList<>();
        roleList.add(2);
        roleList.add(3);
        List listByRoleId = mapper.findListByRoleId_foreach_list(roleList);
        for(User user:listByRoleId){
            System.out.println("集合======="+user.getUserName()+"   "+user.getUserRole());
        }
    }
    @Test
    public void getUserListFen(){
        //分页显示
        String userName="";
        Integer roleId=null;
        Integer pageSize=3;
        Integer currentPageNo=0;
        List userListFen = mapper.getUserListFen(currentPageNo, pageSize, userName, roleId);
        for(User user:userListFen){
            System.out.println("分页显示====="+user.getUserName()+"  "+user.getUserRole());
        }
    }
}


Mybatis---框架搭建---增删查改_第1张图片

你可能感兴趣的:(Mybatis框架)