4.8、Mybatis数据库基本操作示例
请大家根据需要的功能分别在StudentMapper.xml映射文件和测试程序文件中添加相应代码
1、模糊查询信息:
在映射文件中添加的代码(为了防止SQL注入,我们使用concat('%',#{value},'%')函数对模糊查询字符串进行了拼接:
<!-- 配置查询功能,相当于一个名称为findStudentByName(String stuname)的方法 --> <select id="findStudentByName" parameterType="String"resultType="entity.Student"> select * from student where stuname like concat('%',#{value},'%') </select> |
在测试类文件中添加的代码(对个别系统中出现的中文乱码问题,我们在这里进行了简单处理):
List<Student> stu=ssion.selectList("entity.findStudentByName","z"); System.out.println(new String(stu.get(0).getStuname().getBytes("iso-8859-1"),"gbk")); |
从查询结果来看,使用模糊查询可以从数据库中查询出来一个对象集合。
2、更新信息
在映射文件中添加的代码:
<!-- 配置更新功能,相当于一个名称为updateStudent(entity.Student student)的方法 --> <select id="updateStudent" parameterType="entity.Student"> update student set stuname=#{stuname},stuage=#{stuage},phone=#{phone} where stuid = #{stuid} </select> |
在测试类文件中添加的代码:
public class Test { public static void main(String[] args)throws Exception { //修改学生信息 Student s=new Student(); s.setStuname("job"); s.setStuage(23); s.setPhone("15988888888"); s.setStuid(7); new Test().updateStudent(s); } public void updateStudent(Student s)throws Exception{ InputStream inp=Resources.getResourceAsStream("mybatis-config.xml"); SqlSessionFactory sqlsession=new SqlSessionFactoryBuilder().build(inp); SqlSession ssion=sqlsession.openSession(); //利用会话对象的更新功能从数据库中更新数据 ssion.update("entity.updateStudent",s); //提交更新 ssion.commit(); ssion.close(); } } |
从结果来看。我们正确的更新了id为7的学生的信息
3、添加信息
在映射文件中添加的代码:
<!-- 配置插入功能,名称为addStudent(entity.Student student)的方法 --> <select id="addStudent" parameterType="entity.Student"> insert into student(stuid,stuname,stuage,phone) values(null,#{stuname},#{stuage},#{phone}) </select> |
在测试类文件中添加的代码:
public class Test { public static void main(String[] args)throws Exception { //添加学生信息 Student s=new Student(); s.setStuname("tom"); s.setStuage(30); s.setPhone("15959595959"); new Test().addStudent(s); }
public void addStudent(Student s)throws Exception{ InputStream inp=Resources.getResourceAsStream("mybatis-config.xml"); SqlSessionFactory sqlsession=new SqlSessionFactoryBuilder().build(inp); SqlSession ssion=sqlsession.openSession(); //利用会话对象的添加功能往数据库中添加数据 ssion.insert("addStudent", s); //提交更新 ssion.commit(); ssion.close(); } } |
从结果来看。我们正确的添加了新的学生的信息
4、删除信息
在映射文件中添加的代码:
<!-- 配置删除功能,名称为delStudentById(entity.Student student)的方法 --> <select id="delStudent" parameterType="entity.Student"> delete from student where stuid=#{stuid} </select> |
在测试类文件中添加的代码:
public class Test { public static void main(String[] args)throws Exception { //删除学生信息 Student s=new Student(); s.setStuid(6); new Test().delStudent(s); }
public void delStudent(Student s)throws Exception{ InputStream inp=Resources.getResourceAsStream("mybatis-config.xml"); SqlSessionFactory sqlsession=new SqlSessionFactoryBuilder().build(inp); SqlSession ssion=sqlsession.openSession(); //利用会话对象的删除功能从数据库中删除数据 ssion.delete("entity.delStudent",s);
//提交更新 ssion.commit(); ssion.close(); } } |

