Mybatis的CRUD操作(基于注解)

CRUD操作:增删改查

例子(记得导入mybatis和MYSQL的jar包):

javabean:

package com.zw.mybatis;

public class Students {
private int GENDER;
private String SNAME;
private int SID;
public int getGENDER() {
	return GENDER;
}
public void setGENDER(int gENDER) {
	GENDER = gENDER;
}
public String getSNAME() {
	return SNAME;
}
public void setSNAME(String sNAME) {
	SNAME = sNAME;
}
public int getSID() {
	return SID;
}
public void setSID(int sID) {
	SID = sID;
}

public Students() {
}
public Students(int sID, String sNAME ,int gENDER) {
	GENDER = gENDER;
	SNAME = sNAME;
	SID = sID;
}

}
mybatis配置文件 conf.xml

  
  
  
     
     
      
      
          
              
              
                  
                  
                  
                  
              
          
      
      
     
        
       
      


Mapper类:

package com.zw.mybatis;

import org.apache.ibatis.annotations.Insert;

public interface StudentsMapper {
	@Insert("INSERT INTO STUDENTS(SID,SNAME,GENDER) VALUES(#{SID},#{SNAME},#{GENDER})")
public int add(Students students);
}

测试类:

package com.zw.mybatis;

import java.io.InputStream;
import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class Test {

    public static void main(String[] args) {
        String resourse = "conf.xml";
        InputStream is = Test.class.getClassLoader().getResourceAsStream(resourse);
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
        SqlSession session = factory.openSession(true);
        StudentsMapper sm=session.getMapper(StudentsMapper.class);
        //这个add代表受影响的行数
        int add=sm.add(new Students(3,"zw",1));
        session.commit();
        //测试结果应为1
        session.close();
        System.out.println(add);
    }

}





你可能感兴趣的:(Mybatis)