Mybatis 注解@select,@detele,@update,@insert的简单应用

Mybatis基于注解方式实现CRUD(增删查改)操作,相较于传统的XML方式,能有效地简化代码,并更有利于代码维护,且可读性更高!
接下来,将通过注解的方式来实现基本的增删查改操作。

Step1 创建了新的数据库

创建数据库ssm20181229test,并创建了table:user,user表结构和表内容如下:
Mybatis 注解@select,@detele,@update,@insert的简单应用_第1张图片Mybatis 注解@select,@detele,@update,@insert的简单应用_第2张图片

Step2 在eclipse下创建了maven工程:mybatis20190102testAnnotation。

完整的工程结构目录如下:
Mybatis 注解@select,@detele,@update,@insert的简单应用_第3张图片

Step3配置pom.xml

代码如下:


  4.0.0
  com.mybatis
  mybatis20190102testAntotation
  0.0.1-SNAPSHOT
  
   
    
         
               org.apache.maven.plugins
               maven-compiler-plugin 
               3.8.0             
         	   
         	                   
                 10     
                 10   
    		         
          
      
  
  
  
  	
  		com.mybatis
 		pomModule
 		0.0.1-SNAPSHOT
  	
  

为了图方便,我这里直接引入了我之前统一配置的pomModule工程的依赖,pomModule工程中引入了SSM框架的全部依赖,详情参考我的博客:解决maven项目中pom.xml添加依赖文件的繁琐操作的办法

Step4 创建mybatis.xml配置文件

在src/main/resources源文件下创建了mybatis.xml配置文件,代码如下:




	
		
			
			
				
				
				
				
			
		
	

	
		
		
		
		
		
	


Step5 创建User.java类

代码如下:

package com.cr.pojo;
public class User {
	private int userId;
	private String userName;
	private String userPassword;
	private int userAge;
	private String userEmail;
	
	public int getUserAge() {
		return userAge;
	}
	public void setUserAge(int userAge) {
		this.userAge = userAge;
	}
	public String getUserEmail() {
		return userEmail;
	}
	public void setUserEmail(String userEmail) {
		this.userEmail = userEmail;
	}
	public int getUserId() {
		return userId;
	}
	public void setUserId(int userId) {
		this.userId = userId;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getUserPassword() {
		return userPassword;
	}
	public void setUserPassword(String userPassword) {
		this.userPassword = userPassword;
	}
}

Step6 创建UserMapper接口

package com.cr.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.cr.pojo.User;

public interface UserMapper
{
	//selectAll
	@Select("select * from user")
	public List getAllUsers();
	//select
	@Select("select * from user where userId = #{userId}")
	public User getUserById(int userId);
	
	//insert
	@Insert("insert into user(userName,userPassword,userAge,userEmail) "
			+ "values(#{userName},#{userPassword},#{userAge},#{userEmail}) ")
	public void insertUser(User user);
	
	//delete
	@Delete("delete from user where userId = #{userId}")
	public void deleteUserById(int userId);
	
	//update
	@Update("UPDATE USER SET userName = #{userName},userPassword = #{userPassword},userAge = #{userAge},userEmail = #{userEmail}" + 
			"WHERE userId = #{userId}")
	public void updateUser(User user);
}

step7创建测试类:TestAnnotation.java

代码如下:

package com.cr.main;

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 com.cr.mapper.UserMapper;
import com.cr.pojo.User;

public class TestAnnotation {
	 private static SqlSessionFactory sqlSessionFactory;
	    private static Reader reader;
	    

	    static {
	        try {
	            reader = Resources.getResourceAsReader("mybatis.xml");
	            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	    }

	    public static SqlSessionFactory getSession() {
	        return sqlSessionFactory;
	    }

	    /**
	     * @param args
	     */
	    public static void main(String[] args) {
// 		   testSelectAll();
//	       testSelect(2);
//	       testInsert();
//	       testDelete(12);
	       testUpdate();
	    }
	    
	    
	    //select查询测试模块:根据id获得User对象
	    private static void testSelect(int userId) 
	    {	
	    	 SqlSession session = sqlSessionFactory.openSession();
		        try 
		        {
		        	UserMapper userMapper = session.getMapper(UserMapper.class);
		        	User user = userMapper.getUserById(userId);
		        	if(user != null)
		        	{
		        		System.out.println(user.getUserId()+"||"+user.getUserName()+"||"+user.getUserPassword()+"||"+user.getUserAge()
		        		+"||"+user.getUserEmail());
		        	}
		        	else
		        	{
		        		System.out.println("userId为"+userId+"的用户不存在!可能未创建或者已经被删除。");
		        	}

		        } finally {
		            session.close();
		        }
	    }
	    //delete查询测试模块:
	    private static void testDelete(int userId) 
	    {
	    	SqlSession session = sqlSessionFactory.openSession();
	        try 
	        {
	        	UserMapper userMapper = session.getMapper(UserMapper.class);
	        	System.out.println("Before delete:");
	        	testSelect(userId);
	        	userMapper.deleteUserById(userId);
	        	//注意这里需要提交session
	        	session.commit();
	        	System.out.println("After delete:");
	        	//判断是否删除成功
	        	testSelect(userId);
	        } finally {
	            session.close();
	        }
	    }
	    //insert测试模块:向user表中插入行
	    private  static void testInsert()
	    {	
	    	//构造要插入的user对象
	       User user = new User();
	       user.setUserId(0);
	       user.setUserName("NewName");
	       user.setUserEmail("[email protected]");
	       user.setUserAge(999);
	       user.setUserPassword("221111");
	       
	    	SqlSession session = sqlSessionFactory.openSession();
	        try 
	        {
	        	UserMapper userMapper = session.getMapper(UserMapper.class);
	        	System.out.println("Before insert:");
	        	testSelectAll();
	        	userMapper.insertUser(user);
	        	//注意这里需要提交session
	        	session.commit();
	        	System.out.println("After insert:");
	        	testSelectAll();
	        } finally {
	            session.close();
	        }
	    }
	    //update测试模块
	    private static void testUpdate()
	    {	
	    	   User user = new User();
		       user.setUserId(3);
		       user.setUserName("zhoujielun111");
		       user.setUserEmail("[email protected]");
		       user.setUserAge(999);
		       user.setUserPassword("221111");
	    	SqlSession session = sqlSessionFactory.openSession();
	        try 
	        {	
	        	UserMapper userMapper = session.getMapper(UserMapper.class);
	        	System.out.println("Before update:");
	        	testSelect(user.getUserId());
	        	userMapper.updateUser(user);
	        	//注意这里需要提交session
	        	session.commit();
	        	System.out.println("After update:");
	        	testSelect(user.getUserId());
	        } finally {
	            session.close();
	        }
	    }
	    
	    //selectAll测试模块
	    private static void testSelectAll()
	    {
	    	SqlSession session = sqlSessionFactory.openSession();
	        try 
	        {
	        	UserMapper userMapper = session.getMapper(UserMapper.class);
	        	System.out.println("All users:");
	        	List users = userMapper.getAllUsers();
	        	for(User user:users)
	        	{
	        		System.out.println(user.getUserId()+"||"+user.getUserName()+"||"+user.getUserPassword()+"||"+user.getUserAge()
	        		+"||"+user.getUserEmail());
	        	}
	        } finally {
	            session.close();
	        }
	    }
}

结语

至此,创建工作全部完成。(2019.01.02)

你可能感兴趣的:(mybatis)