insert into users(name,age) values(#{name},#{age})
update users set name=#{name},age=#{age} where id=#{id}
delete from users where id=#{id}
4.实体类配置(一定要添加空的构造方法)
public class User {
private int id;
private String name;
private int age;
public User() {
}
public User(String name, int age) {
this.name = name;
this.age = age;
}
public User(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
//省略get和set方法
}
5.配置测试类(本案例使用junit测试 )
public class JunitTest {
/**
* 封装session
*/
public static SqlSession getSession(){
String resource = "conf.xml";
InputStream is = JunitTest.class.getClassLoader().getResourceAsStream(resource);
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
// SqlSession session = factory.openSession(true) 自动提交更新
SqlSession session = factory.openSession(); //默认为手动提交更新
return session;
}
/**
* 封装statement
*/
public static String getStatement(String statement){
return "mybatisIDUS."+statement;
}
/**
* 插入一条数据
*/
@Test
public void insert(){
String statement = "mybatisIDUS.insertUser";
SqlSession session = getSession();
int result = session.insert(statement, new User("wangwu", 19));
if (result==1){
session.commit();
session.close();
System.out.println("插入成功");
}
}
/**
* 通过id查询单个数据
*/
@Test
public void select(){
String statement = "mybatisIDUS.getUser";
SqlSession session = getSession();
User user = session.selectOne(statement, 1);
System.out.println(user);
session.close();
}
/**
* 更新数据
*/
@Test
public void update(){
SqlSession session = getSession();
String statement = getStatement("updateUser");
int result = session.update(statement, new User(10, "wangwu", 44));
if (result==1){
session.commit();
session.close();
System.out.println("更新成功");
}
}
/**
* 通过id删除一条
*/
@Test
public void delete(){
SqlSession session = getSession();
String statement = getStatement("deleteUser");
int result = session.delete(statement, 1);
if (result==1){
session.commit();
session.close();
System.out.println("删除成功");
}
}
}