Mybatis模板(已优化)适合小白

1.搭建数据库(我用的是mysql 5.5)

#创建一个mybatis数据库
create database `mybatis`;

#使用mybatis数据库
use `mybatis`;

#创建一个user表,有id、username、password三个字段
create table `user`(
    `id` int(10) not null primary key auto_increment,
    `username` varchar(30) default null,
    `password` varchar(30) default null
)engine=InnoDB default charset=utf8;

#插入数据
insert into `user`(`username`,`password`) values
('张三',123456),
('李四',123456),
('王五',123456);

2.导入mybatis相关的jar包(COPY,建议创建一个父子项目)


        

            mysql
            mysql-connector-java
            8.0.19
        

        
            org.mybatis
            mybatis
            3.4.2
        

        
            junit
            junit
            4.12
        

        
            log4j
            log4j
            1.2.12
        
    


    
    
        
            src/main/resources
            
                **/*.properties
                **/*.xml
            
            true
        
        
            src/main/java
            
                **/*.properties
                **/*.xml
            
            true
        
    

3.编写MyBatisUtil工具类(COPY,低层原理还没有搞懂,直接复制的条件是要创建一个mybatis-config.xml文件  文件名要一致)

package com.kuang.utils;

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;
    static{
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            //SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);因为重复定义导致空指针异常
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }

}

4.1编写db.properties配置文件(COPY,是后来优化的)

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
username=root
password=root

4.2编写log4j.properties配置文件(COPY,是后来优化的)

#将等级为DEBUG的日志信息输出到console和file这两个目的地,console和file的定义在下面的代码
log4j.rootLogger=DEBUG,console,file

#控制台输出的相关设置
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%c]-%m%n

#文件输出的相关设置
log4j.appender.file = org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./log/kuang.log
log4j.appender.file.MaxFileSize=10mb
log4j.appender.file.Threshold=DEBUG
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n

#日志输出级别
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

4.3编写MyBatis核心配置文件(COPY,mybatis-config.xml,已优化)









        
    



        
    
    
        
            
            

                
                
                
                
            
        
    
    

        
    

5.编写User实体类

public class User {
   
//注意 类中定义的变量名要和数据库中的字段名一致
   private int id;  //id
   private String username;   //姓名
   private String password;   //密码
   
   //构造,有参,无参
   //set/get
   //toString()
   
}

6.编写Mapper接口类(Mapper.java)

package com.kuang.dao;

import com.kuang.pojo.User;

import java.util.List;

public interface Mapper {
    List getUserList();
}

7.编写mapper.xml配置文件





    

8.编写测试类

package com.kuang.dao;

import com.kuang.pojo.User;
import com.kuang.utils.Mybatise;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class UserDaoTest {

//后来优化
    static Logger logger = Logger.getLogger(MapperDaoTest.class);
    @Test
    public void test(){
        logger.info("info:进入selectUser方法");
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        UserDao mapper = sqlSession.getMapper(Mapper.class);
        List userList = mapper.getUserList();
        for(User user:userList){
            System.out.println(user);
        }
        //sqlSession.commit();增删改需要添加事务
        sqlSession.close();
    }
}

 

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