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); } }
作者:程序员小波与Bug
出处:https://codetrips.cn
本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。如有问题,可以邮件:caiya928@aliyun.com
QQ:1419901425 联系我
如果喜欢我的文章,请关注我的公众号:程序员小波与Bug