创建数据表映射类People,如下
package org.test.mybatis.model;
public class People {
private int id;
private String userName;
private String passWord;
private String realName;
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 String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
}
创建数据表操作映射器,如下:
package org.test.mybatis.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.test.mybatis.model.People;
public interface PeopleMapper {
@Insert("insert into people (userName,passWord,realName) values (#{userName},#{passWord},#{realName})")
void insertPeople(People people);
}
创建测试入口类,如下
package org.test.mybatis.root;
import java.io.IOException;
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.test.mybatis.mapper.PeopleMapper;
import org.test.mybatis.model.People;
public class Main {
public static void main(String[] args) throws IOException {
String resource = "mybatis.configuration.xml";
Reader reader = Resources.getResourceAsReader(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
.build(reader);
SqlSession session = sqlSessionFactory.openSession();
PeopleMapper pmp = session.getMapper(PeopleMapper.class);
People pp=new People();
pp.setPassWord("xiaoshagua");
pp.setRealName("xiaoshagua");
pp.setUserName("xiaoshagua");
pmp.insertPeople(pp);
session.commit();
}
}
当执行Main类时,数据库将多出一条数据