Mybatis用法详解(配置和注解的使用)

mybatis是持久层框架

使用方法(基于xml配置)

1.添加依赖(Maven)

    
    
        mysql
        mysql-connector-java
        5.1.37
    
    
    
        org.mybatis
        mybatis-spring
        ${mybatis-spring-version}
    
    
    
        org.mybatis
        mybatis
        ${mybatis-version}
    
     
    
        org.mybatis.generator
        mybatis-generator-core
        1.3.2
    

2.建立数据库、表
CREATE DATABASE testdatabase;
USE testdatabase;
CREATE TABLE user(id INT PRIMARY KEY AUTO_INCREMENT, userName VARCHAR(20) NOT NULL, userAge INT NOT NULL);
INSERT INTO user(userName, userAge) VALUES('Xiaoxin', 21);
INSERT INTO user(userName, userAge) VALUES('Xiaoming', 22);
3.表的实体类
package com.xiaoxin.demo.dto;

public class User {
	private int id;
    private String userName;
    private int userAge;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}
	public int getUserAge() {
		return userAge;
	}
	public void setUserAge(int userAge) {
		this.userAge = userAge;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", userName=" + userName + ", userAge=" + userAge + "]";
	}
}

4.添加Mybatis的配置文件



     
         
     
	
    
        
        
        
         
            
             
            
            
            
            
            
            
            
            
        
    
    
    
        
    

5.定义操作user表的映射文件,第四步已经注册到mybatis的配置文件中去了




    

6.测试
package com.xiaoxin.demo.dto;

import java.io.Reader;

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 org.junit.Test;

public class TestUser {
	@Test
	public void testUser() throws Exception{
		 SqlSessionFactory sqlSessionFactory;
	     Reader reader; 
	     String resource = "spring/configuration.xml";
	     //加载一个流
	     reader= Resources.getResourceAsReader(resource);
	     //生成sqlSessionFactory工厂
	     sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
	     SqlSession session = sqlSessionFactory.openSession();
	     User user =(User) session.selectOne("com.xiaoxin.demo.dto.selectUserByID", 1);
	     System.out.print(user.toString());
	    session.close();
		
	}
	

}

连接数据库成功查询到数据
Mybatis用法详解(配置和注解的使用)_第1张图片

CRUD操作汇总




    
     
    
    
    		insert into user(userName,userAge) values(#{userName},#{userAge});
    
	
    
    		update user set userAge=#{userAge},userName=#{userName} where id=#{id}
    
    
    
    	delete from user where id=#{id}
    
    
测试
package com.xiaoxin.demo.dto;

import java.io.Reader;
import java.util.List;

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 org.junit.Test;

public class TestUser {
	@Test
	public void testUser() throws Exception{
		 SqlSessionFactory sqlSessionFactory;
	     Reader reader; 
	     String resource = "spring/configuration.xml";
	     //加载一个流
	     reader= Resources.getResourceAsReader(resource);
	     //生成sqlSessionFactory工厂
	     sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
	     SqlSession session = sqlSessionFactory.openSession();
	     //插入
//	     User user1 = new User();
//	     user1.setUserName("Xiaohong");
//	     user1.setUserAge(20);
//	     session.insert("com.xiaoxin.demo.dto.insertUser", user1);
//	     // session.commit();一定要执行不然在数据库中没有信息!!!!!
//	     session.commit();
	    //更新
	     //把Xiaohong的姓名改为Xiaohong101年龄改为44 Xiaohong的id是13
//	     User user3 = new User();
//	     user3.setUserName("Xiaohong101");
//	     user3.setUserAge(44);
//	     user3.setId(16);
//	     session.update("com.xiaoxin.demo.dto.updateUser",user3);
//	     session.commit();
	     
	    //删除
	     session.delete("com.xiaoxin.demo.dto.deleteUser",16);
	     session.commit();
	     //查询数据库全部的信息
	     List user2 = session.selectList("com.xiaoxin.demo.dto.selectUserAll");
	     for(User user:user2){
	    	 System.out.println(user.toString());
	     }
	    session.close();
		
	}
	

}
以上自己测试过全部成功,但是xml的配置过程中自己出错了很多,调试了很多次才成功调试出来,下面学习基于注解的写法

Mybatis的注解用法


1.定义SQL映射的接口
package com.xiaoxin.demo.mapper;

import java.util.List;

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 com.xiaoxin.demo.dto.User;

public interface UserMapper {
	@Select("select * from user")
	public List getSelectUser();
	@Update("UPDATE user set userName=#{userName},userAge=#{userAge} where id=#{id}")
	public void getUpdateUser(User user);
	@Insert("insert into user(userName,userAge) values(#{userName},#{userAge});")
	public void getInsertUser(User user);
	@Delete("DELETE FROM user where id=#{id}")
	public void getDeleteUser(int id);
	

}
2.在mybatis的配置文件中注册这个映射接口(注意是class!!)
 
        
        
    

在Dao类中调用(这里是测试)
package com.xiaoxin.demo.dto;

import java.io.IOException;
import java.io.Reader;
import java.util.List;

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 org.junit.Test;

import com.xiaoxin.demo.mapper.UserMapper;

public class TestUserAnnotation {
	
	@Test
	public void testUser() throws IOException{
		
		 SqlSessionFactory sqlSessionFactory;
	     Reader reader; 
	     String resource = "spring/configuration.xml";
	     //加载一个流
	     reader= Resources.getResourceAsReader(resource);
	     //生成sqlSessionFactory工厂
	     sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
	     SqlSession session = sqlSessionFactory.openSession();
	     
	     UserMapper userMapper = session.getMapper(UserMapper.class);
	     //插入
//	     User user = new User();
//	     user.setUserName("xinxin");
//	     user.setUserAge(20);
//	     userMapper.getInsertUser(user);
//	     session.commit();
	     //删除
//	     userMapper.getDeleteUser(21);
//	     session.commit();
	     //更新将id为19的姓名不变 年龄改为23
//	     User user = new User();
//	     user.setId(19);
//	     user.setUserName("xinxin");
//	     user.setUserAge(23);
//	     userMapper.getUpdateUser(user);
//	     session.commit();
	     //查询
	     List users = userMapper.getSelectUser();
	     for(User user2 :users){
	    	 System.out.println(user2.toString());
	     }
	     session.close();
	}

}

测试成功







你可能感兴趣的:(Java)