mybatis学习之CLOB、BLOB处理及多参数方法映射

这篇博客介绍了如何在MyBatis中操作CLOB和BLOB数据类型,包括在MySQL中对应的longtext和longblob类型。文章详细展示了实体模型的创建、 Dao接口的定义以及JUnit测试案例。此外,还讲解了MyBatis如何进行多参数查询,并给出了相应的Dao接口和mapper映射示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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);
        }
    }

 

转载于:https://my.oschina.net/caiya928/blog/784079

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值