使用逆向工程,帮我们更快的建立pojo类、mapper接口及xml映射文件等,无需手写,替代了一部分的mybatis功能。
生成与自己项目结构相同的文件
/**
* 1.查询所有学生信息
*/
@Test
public void getStudent(){
//查询所有,查询条件
List<Student> studentList = studentMapper.selectByExample(null);
System.out.println(studentList);
}
执行结果:
/**
* 2.根据姓名查学生信息
*/
@Test
public void getStuByName(){
//添加条件
StudentExample exp = new StudentExample();
exp.createCriteria().andSnameEqualTo("静静");
List<Student> studentList = studentMapper.selectByExample(exp);
System.out.println(studentList);
}
执行结果:
/**
* 3.根据姓名,sid查学生信息
*/
@Test
public void getStuByNameSid(){
//添加条件
StudentExample exp = new StudentExample();
exp.createCriteria().andSnameEqualTo("大林子").andSidEqualTo(3);
List<Student> studentList = studentMapper.selectByExample(exp);
System.out.println(studentList);
}
执行结果:
/**
* 根据主键删除
*/
@Test
public void deleteByKey(){
int i = studentMapper.deleteByPrimaryKey(10);
System.out.println(i);
sqlSession.commit();
sqlSession.close();
}
执行结果:
/**
* 根据自定义条件删除
*/
@Test
public void delete(){
StudentExample exp = new StudentExample();
//添加姓名条件
exp.createCriteria().andSnameEqualTo("阿飞");
int i = studentMapper.deleteByExample(exp);
System.out.println(i);
sqlSession.commit();
sqlSession.close();
}
执行结果:
/**
* 增加学生信息
*/
@Test
public void add(){
Student student = new Student();
//sid是主键,自增,可以不写
student.setSname("章子");
student.setAge(20);
student.setCid(3);
int i = studentMapper.insert(student);
System.out.println(i);
sqlSession.commit();
sqlSession.close();
}
执行结果:
@Test
public void add2(){
Student student = new Student();
student.setSname("关晓彤");
student.setAge(18);
int i = studentMapper.insertSelective(student);
System.out.println(i);
sqlSession.commit();
sqlSession.close();
}
执行结果:
/**
* 根据条件修改
*/
@Test
public void update(){
Student student = new Student();
//主键不可省略(不可以修改为null)
student.setSid(15);
student.setAge(22);
StudentExample exp = new StudentExample();
exp.createCriteria().andSnameEqualTo("章子");
//将姓名为"章子"的信息修改为student
int i = studentMapper.updateByExample(student,exp);
System.out.println(i);
sqlSession.commit();
sqlSession.close();
}
执行结果:
/**
* 根据条件修改某列
*/
@Test
public void update2(){
Student student = new Student();
student.setAge(22);
StudentExample exp = new StudentExample();
exp.createCriteria().andSnameEqualTo("老王");
//将姓名为"老王"的信息修改:修改年龄列
int i = studentMapper.updateByExampleSelective(student,exp);
System.out.println(i);
sqlSession.commit();
sqlSession.close();
}
执行结果:
/**
* 根据主键修改
*/
@Test
public void update3(){
Student student = new Student();
student.setSid(4);
student.setSname("岳岳");
//根据主键sid,修改这一条所有数据
int i = studentMapper.updateByPrimaryKey(student);
sqlSession.commit();
sqlSession.close();
}
执行结果:
/**
* 根据主键修改固定列
*/
@Test
public void update4(){
Student student = new Student();
student.setSid(8);
student.setCid(1);
//根据主键sid,修改固定列cid的值
int i = studentMapper.updateByPrimaryKeySelective(student);
System.out.println(i);
sqlSession.commit();
sqlSession.close();
}
执行结果:
原文:https://www.cnblogs.com/soft-test/p/14854138.html