一.Clob與Blob應用.
Student類添加兩個屬性, byte[] pic, string remark; mybatis_Student表添加兩個字段pic longblob, remark longtext(MySQL的clob類型)
完成對student表的添加與查詢.
1.StudentMapper類添加方法
- public void addStudent(Student student);
2.StudentMapper.xml配置
- <select id="addStudent" parameterType="Student">
- insert into mybatis_Student (name, age, remark, pic,grade_id,address_id)
- values (#{name},#{age},#{remark}, #{pic},#{grade.id},#{address.id})
- </select>
3.測試添加方法
- @Test
- public void testAddStudent(){
- logger.info("添加學生");
- StudentMapper mapper = session.getMapper(StudentMapper.class);
- Student stu = new Student();
- stu.setName("你是誰");
- stu.setAge(13);
- Address addr = new Address();
- addr.setId(1);
- stu.setAddress(addr);
- Grade grade = new Grade();
- grade.setId(1);
- stu.setGrade(grade);
- stu.setRemark("判明顯而易見大煞風景期日進口非城奪在城城在風景點赤膽忠心右吸在");
- try {
- stu.setPic(FileUtil.readFile("e:/1.jpg"));
- mapper.addStudent(stu);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- package com.skymr.mybatis.util;
- import java.io.FileInputStream;
- import java.io.InputStream;
- public class FileUtil {
- public static byte[] readFile(String filePath) throws Exception{
- InputStream is = null;
- try{
- is = new FileInputStream(filePath);
- byte[] ret = new byte[is.available()];
- is.read(ret);
- return ret;
- }
- finally{
- if(is != null){
- try{
- is.close();
- }catch(Exception e){}
- }
- }
- }
- }
4.測試查詢方法
使用以前的方法就可以了
- @Test
- public void testGetStudent(){
- logger.info("獲取學生");
- StudentMapper mapper = session.getMapper(StudentMapper.class);
- Student stu = mapper.getStudent(4);
- logger.info(stu.toString());
- }
二.Mapper方法的多參數傳入.
前面學習的時候Mapper方法的參數要么是一個int類型的id,要么沒有,要么傳入一個Map,Map應用得多,也可以將多個參數放到Map里傳入,也可以使用這種方式:
- public Student getStudent(String name, int age);
- <select id="getStudent1" resultMap="stuMapWithAddr">
- select * from mybatis_Student where name like #{param1} and age=#{param2}
- </select>
因為有多個參數,所以不能指定parameterType了