MyBatis 使用简记

5,238 阅读2分钟

MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的持久层框架。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以对配置和原生Map使用简单的 XML 或注解,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。

官网:www.mybatis.org/

Hello Mybatis

首先通过一个项目实例熟悉Mybatis的基础使用吧。

项目结构

HelloMybatis项目结构

配置Maven依赖



    junit
    junit
    3.8.1
    test




    org.mybatis
    mybatis
    3.4.1




    mysql
    mysql-connector-java
    6.0.5




    log4j
    log4j
    1.2.17

配置mybatis-config.xml




    
        
            
            
                
                
                
                
                
                
                
                
            
        
    
    
    
        
    

创建数据表

CREATE TABLE `user` (
  `id` int(11) NOT NULL,
  `name` varchar(255) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

映射文件User.xml




    user
    
        SELECT * FROM 
    

实体对象User

package com.zju.meta;
/** 用户类 */
public class User {
    private Integer id;
    private String name;
    private Integer age;
    private String password;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", password='" + password + '\'' +
                '}';
    }
}

Dao类

package com.zju.dao;
public interface UserDao {
    List getAllUser();
}

测试类

public class Main {
    public static void main(String[] args) throws IOException {
        String resource="mybatis-config.xml";
        InputStream inputStream= Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();
        try {
            UserDao userDao = session.getMapper(UserDao.class);
            List users= userDao.getAllUser();
            System.out.println(users);
        } finally {
            session.close();
        }
    }
}

日志配置

通过以下配置,可以将实际执行的SQL语句打印在日志中,方便排查问题。

# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
# 指定Mapper包范围的日志级别 
log4j.logger.com.zju.dao=DEBUG
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m

测试

DEBUG [main] - ==>  Preparing: SELECT * FROM user 
DEBUG [main] - ==> Parameters: 
DEBUG [main] - <==      Total: 3
[com.zju.meta.User@17211155, com.zju.meta.User@b3d7190, com.zju.meta.User@5fdba6f9]

Spring+Mybatis

项目结构

SpringMybatis项目结构

配置Maven依赖



  junit
  junit
  3.8.1
  test


  org.springframework
  spring-context
  4.3.1.RELEASE


  org.springframework
  spring-tx
  4.3.1.RELEASE


  org.springframework
  spring-jdbc
  4.3.1.RELEASE



  org.mybatis
  mybatis-spring
  1.3.0



  org.mybatis
  mybatis
  3.4.1



  mysql
  mysql-connector-java
  5.1.39



  com.alibaba
  druid
  1.0.18



  log4j
  log4j
  1.2.17


配置mybatis-config.xml




    
        
        
    
    
        
    

配置spring-config.xml



    
    
    
    
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
    
    
    
        
        
    
    
        
        
    
    
        
        
    

配置privateSettings.properties

db.url=jdbc:mysql://localhost:3307/work?characterEncoding=UTF-8
db.user=root
db.pass=
db.maxActive=10
db.initialSize=2
db.minIdle=2
db.maxWait=60000
db.timeBetweenEvictionRunsMillis=3000
db.minEvictableIdleTimeMillis=300000
db.validationQuery=SELECT 'x' FROM DUAL
db.testWhileIdle=true
db.testOnBorrow=false
db.testOnReturn=false
db.filters=stat,wall,log4j

Service类

@Service
public class UserService {
    @Resource
    private UserDao userDao;
    public List getAllUser(){
        return userDao.getAllUser();
    }
}

测试类

public class Main {
    public static void main(String[] args){
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
        UserService service = (UserService) context.getBean("userService");
        System.out.println(service.getAllUser());
    }
}

日志配置




    
        
            
        
    
    
        
    
    
        
        
    

测试

DEBUG [main] - ==>  Preparing: SELECT * FROM user 
DEBUG [main] - ==> Parameters: 
DEBUG [main] - <==      Total: 3
[com.zju.meta.User@7b4c50bc, com.zju.meta.User@5884a914, com.zju.meta.User@50378a4]

相关问题

字符串对比

在Mybatis的if test语句中如果需要对比字符串,可以组合使用单引号和双引号,比如

空指针报警

在运行Druid时可能出现Cannot resolve com.mysq.jdbc.Connection.ping method. Will use 'SELECT 1' instead.java.lang.NullPointerException报警

使用5.1.x版本的mysql-connector-java可以解决

Spring和Mybatis整合时无法读取properties

因为MapperScannerConigurer实际是在解析加载bean定义阶段的,这个时候要是设置sqlSessionFactory的话,会导致提前初始化一些类,这个时候,PropertyPlaceholderConfigurer还没来得及替换定义中的变量,所以导致把表达式当作字符串复制了。

把org.mybatis.spring.SqlSessionFactoryBean的id修改为’sqlSessionFactoryBean’,使得该值不是’sqlSessionFactory’,不然会造成提前初始化。

缺少依赖包错误

  • java.lang.NoClassDefFoundError: org/springframework/dao/support/DaoSupport 错误

    缺失spring-tx包

  • java.lang.NoClassDefFoundError: org/springframework/jdbc/datasource/TransactionAwareDataSourceProxy 错误

    缺失spring-jdbc包