mybatis學習之CLOB、BLOB處理及多參數方法映射


CLOB數據mysql對應數據類型為longtext、BLOB類型為longblob:

model實體:

...
private Integer id;
private String name;
private int age;

private byte[] pic; // 映射blob
private String remark; // 映射longtext
...

1、blob、clob數據插入:

<insert id="insertStudent" parameterType="Student">
    insert into t_student values(null,#{name},#{age},#{pic},#{remark})
</insert>

對應Dao接口:

/**
* 插入學生
* @param student
* @return
*/
public int insertStudent(Student student);

junit測試:

@Test
    public void testInsert() throws Exception {
        logger.info("新增學生");
        Student student = new Student();
        student.setAge(12);
        student.setName("晁州");
        student.setRemark("長文本");
        byte[] pic = null;
        try {
            File file = new File("c://test.png");
            InputStream is = new FileInputStream(file);
            pic = new byte[is.available()];
            is.read(pic);
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        student.setPic(pic);
        studentDao.insertStudent(student);
        sqlSession.commit();
    }

2、blob、clob數據查詢(blob數據查詢出來對應java的byte[]):

<select id="getStudentById" parameterType="Integer" resultType="Student">
    select * from t_student where id = #{id}
</select>

Dao接口部分:

@Test
    public void testGet() throws Exception {
        logger.info("查詢學生");
        Student student = studentDao.getStudentById(34);
        System.out.println(student);
        byte[] pic = student.getPic();
        try {
            File file = new File("c://output.png");
            OutputStream os = new FileOutputStream(file);
            os.write(pic);
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

3、mybatis的多參數查詢:

Dao接口部分:

/**
     * 根據姓名和年齡進行查詢(mybatis多參數查詢)
     * @param name
     * @param age
     * @return
     */
    public List<Student> getStudentsBy2Args(String name,Integer age);

對應mapper映射:

<select id="getStudentsBy2Args" resultMap="StudentResult">
    select * from t_student where name like #{param1} and age = #{param2}        <!-- 與方法的參數順序一一對應 -->
</select>

junit測試:

@Test
    public void testGetStudentsBy2Args() throws Exception {
        List<Student> students = studentDao.getStudentsBy2Args("%晁%", 24);
        for (Student student : students) {
            System.out.println("####### "+student);
        }
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM