小峰mybatis(1) 处理clob,blob等。。

一、mybatis处理CLOB、BLOB类型数据

CLOB:大文本类型;小说啊等大文本的;对应数据库类型不一致,有long等;

BLOB:二进制的,图片;电影、音乐等二进制的;

在mysql中:

blob:

longblob:存储的东西比blob更大;

longtext:存储大文本类型的;

新建t_studeng表:

create table t_student(
    id int primary key auto_increment,
    name varchar(20),
    age int,
    pic longblob,
    remark longtext
)

项目结构:

1)jdbc.properties:

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test_demo
jdbc.username=root
jdbc.password=123456

2)mybatis_config.xml:

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE configuration
 3 PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
 4 "http://mybatis.org/dtd/mybatis-3-config.dtd">
 5 <configuration>
 6     <properties resource="jdbc.properties"/>
 7     <!-- 别名 -->
 8     <typeAliases>
 9         <package name="com.cy.model"/>
10     </typeAliases>
11
12     <environments default="development">
13         <environment id="development">
14             <transactionManager type="JDBC" />
15                 <dataSource type="POOLED">
16                     <property name="driver" value="${jdbc.driverClassName}" />
17                     <property name="url" value="${jdbc.url}" />
18                     <property name="username" value="${jdbc.username}" />
19                     <property name="password" value="${jdbc.password}" />
20                 </dataSource>
21         </environment>
22         <environment id="test">
23             <transactionManager type="JDBC" />
24             <dataSource type="POOLED">
25                 <property name="driver" value="${jdbc.driverClassName}" />
26                 <property name="url" value="${jdbc.url}" />
27                 <property name="username" value="${jdbc.username}" />
28                 <property name="password" value="${jdbc.password}" />
29             </dataSource>
30         </environment>
31     </environments>
32
33     <mappers>
34         <package name="com.cy.mapper"/>
35     </mappers>
36 </configuration>

3)Student.java model:

 1 package com.cy.model;
 2
 3 public class Student {
 4     private Integer id;
 5     private String name;
 6     private Integer age;
 7     private byte[] pic;
 8     private String remark;
 9
10     public Integer getId() {
11         return id;
12     }
13     public void setId(Integer id) {
14         this.id = id;
15     }
16     public String getName() {
17         return name;
18     }
19     public void setName(String name) {
20         this.name = name;
21     }
22     public Integer getAge() {
23         return age;
24     }
25     public void setAge(Integer age) {
26         this.age = age;
27     }
28     public byte[] getPic() {
29         return pic;
30     }
31     public void setPic(byte[] pic) {
32         this.pic = pic;
33     }
34     public String getRemark() {
35         return remark;
36     }
37     public void setRemark(String remark) {
38         this.remark = remark;
39     }
40     @Override
41     public String toString() {
42         return "Student [id=" + id + ", name=" + name + ", age=" + age
43                 + ", remark=" + remark + "]";
44     }
45
46
47
48 }

4)获取sqlSession:SqlSessionFactoryUtil.java:

 1 package com.cy.util;
 2
 3 import java.io.IOException;
 4 import java.io.InputStream;
 5
 6 import org.apache.ibatis.io.Resources;
 7 import org.apache.ibatis.session.SqlSession;
 8 import org.apache.ibatis.session.SqlSessionFactory;
 9 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
10
11 public class SqlSessionFactoryUtil {
12     private static SqlSessionFactory sqlSessionFactory;
13
14     public static SqlSessionFactory getSqlSessionFactory(){
15         if(sqlSessionFactory==null){
16             InputStream inputStream=null;
17             try {
18                 inputStream=Resources.getResourceAsStream("mybatis_config.xml");
19                 sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
20             } catch (IOException e) {
21                 e.printStackTrace();
22             }
23         }
24
25         return sqlSessionFactory;
26     }
27
28     public static SqlSession openSession(){
29         return getSqlSessionFactory().openSession();
30     }
31 }

5)测试代码:StudentTest.java: service层:

 1 package com.cy.service;
 2
 3 import java.io.File;
 4 import java.io.FileInputStream;
 5 import java.io.FileOutputStream;
 6 import java.io.InputStream;
 7 import java.io.OutputStream;
 8
 9 import org.apache.ibatis.session.SqlSession;
10 import org.junit.After;
11 import org.junit.Before;
12 import org.junit.Test;
13
14 import com.cy.mapper.StudentMapper;
15 import com.cy.model.Student;
16 import com.cy.util.SqlSessionFactoryUtil;
17
18 public class StudentTest {
19     private SqlSession sqlSession=null;
20     private StudentMapper studentMapper=null;
21
22     @Before
23     public void setUp() throws Exception {
24         sqlSession=SqlSessionFactoryUtil.openSession();
25         studentMapper=sqlSession.getMapper(StudentMapper.class);
26     }
27
28     @After
29     public void tearDown() throws Exception {
30         sqlSession.close();
31     }
32
33     @Test
34     public void testInsertStudent(){
35         Student student=new Student();
36         student.setName("zhangsan");
37         student.setAge(14);
38         student.setRemark("很长的文本...");
39         byte []pic=null;
40         try{
41             File file=new File("I://shoot.png");
42             InputStream inputStream=new FileInputStream(file);
43             pic=new byte[inputStream.available()];
44             inputStream.read(pic);
45             inputStream.close();
46         }catch(Exception e){
47             e.printStackTrace();
48         }
49         student.setPic(pic);
50         studentMapper.insertStudent(student);
51         sqlSession.commit();
52     }
53
54     @Test
55     public void testGetStudentById(){
56         Student student=studentMapper.getStudentById(1);
57         System.out.println(student);
58         byte []pic=student.getPic();
59         try{
60             File file=new File("i://boy.png");
61             OutputStream outputStream=new FileOutputStream(file);
62             outputStream.write(pic);
63             outputStream.close();
64         }catch(Exception e){
65             e.printStackTrace();
66         }
67     }
68
69
70
71
72 }

执行testInsertStudent方法后,查看数据库中插入情况:

执行testGetStudentById获取这个记录,将pic保存到I盘 boy.png,已将数据库中的图片,以流的形式写入到I盘中;

6)StudentMapper.java:

 1 package com.cy.mapper;
 2
 3 import com.cy.model.Student;
 4
 5 public interface StudentMapper {
 6
 7     //插入
 8     public int insertStudent(Student student);
 9
10     //根据id获取student
11     public Student getStudentById(Integer id);
12
13 }

7)StudentMapper.xml mapper映射文件:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.cy.mapper.StudentMapper">

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

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

二、项目中使用log4j:

在项目中加入log4j的jar包,以及配置log4j.properties:

1)log4j.properties配置文件:

1 log4j.rootLogger=info,appender1,appender2
2
3 log4j.appender.appender1=org.apache.log4j.ConsoleAppender
4
5 log4j.appender.appender2=org.apache.log4j.FileAppender
6 log4j.appender.appender2.File=I:/logFile.txt
7
8 log4j.appender.appender1.layout=org.apache.log4j.TTCCLayout
9 log4j.appender.appender2.layout=org.apache.log4j.TTCCLayout  

而且,发现配置文件名必须为log4j.properties;

上面的输入到两个地方:

console;

I盘下面的logFile.txt;

2)测试代码:StudentTest.java:

package com.cy.service;

import org.apache.log4j.Logger;
import org.junit.Test;

public class StudentTest {

    private static Logger logger = Logger.getLogger(StudentTest.class);

    @Test
    public void testLogger(){
        logger.info("测试log4j.....");
    }

    @Test
    public void testOtherLogger(){
        logger.info("测试other log4j.....");
    }
}

运行后console输出:这样信息:

[main] INFO com.cy.service.StudentTest - 测试other log4j.....

查看I盘下面logFile.txt:

时间: 2024-11-03 21:23:07

小峰mybatis(1) 处理clob,blob等。。的相关文章

小峰mybatis(3)mybatis分页和缓存

一.mybatis分页-逻辑分页和物理分页: 逻辑分页: mybatis内置的分页是逻辑分页:数据库里有100条数据,要每页显示10条,mybatis先把100条数据取出来,放到内存里,从内存里取10条:虽然取出的是10条,但是性能不好,几千条上万条没问题,数据量大性能就有问题了:小项目使用没问题:正式的项目数据量都很大就不使用了: 物理分页: 开发的时候用的:拼sql,真正实现分页: 现有数据库记录: 1.逻辑分页 1)测试代码StudentTest2.java: package com.cy

小峰mybatis(2)mybatis传入多个参数等..

一.mybatis传入多个参数: 前面讲传入多个参数都是使用map,hashmap:key value的形式:-- 项目中开发都建议使用map传参: 比如现在通过两个参数,name和age来查询: 通过两个参数来查的,了解下就行了: 数据库中存在t_student记录: 1)测试代码StudentTest.java: @Test public void testSearchStudents() { logger.info("根据name和age查询学生"); List<Stude

小峰mybatis(4)mybatis使用注解配置sql映射器

主流开发还是使用xml来配置:使用注解配置比较快,但是不支持所有功能:有些功能还是得用配置文件: 一.基本映射语句: @Inert @Update @Delete @Select 二.结果集映射语句 项目结够: Student.java model实体类: package com.cy.model; public class Student{ private Integer id; private String name; private Integer age; public Student(

小峰mybatis(5)mybatis使用注解配置sql映射器--动态sql

一.使用注解配置映射器 动态sql: 用的并不是很多,了解下: Student.java 实体bean: package com.cy.model; public class Student{ private Integer id; private String name; private Integer age; public Student(){ } public Student(String name, Integer age){ this.name = name; this.age =

Oracle如何通过dataLink复制远程数据库的CLOB\BLOB字段数据到本地数据库

Oracle不支持直接通过Database Link复制远程数据库表的CLOB/BLOB字段数据到本地数据库. 像如下的SQL是不能执行的.(ipop_topic表有一个CLOB的字段) insert into ipop_topicselect * from [email protected] where application_id=1000 但是,我们可以借助全局临时表,先把数据复制到临时表,再从临时表转移到你的目的表. create global temporary table ipop_

CLOB,BLOB与String互转。

String s1="1231dsdgasd的飒飒大"; Clob c = new SerialClob(s1.toCharArray());//String 转 clob Blob b = new SerialBlob(s1.getBytes("GBK"));//String 转 blob// 也可以这样不传字符集名称,默认使用系统的// Blob b = new SerialBlob(s1.getBytes()); String clobString = c.g

myBatis之Clob &amp; Blob

1. 表结构 1.1 在Mysql中的数据类型,longblob  -->  blob, longtext --> clob 2. 配置文件, 请参考  myBatis之入门示例 3. LOB.java package com.blueStarWei.entity; public class LOB { private Integer id; private byte[] picture;//BLOb --> byte[] private String remark;//CLOB --&

深入浅出JDBC-操作时间与大对象(Clob/Blob)

一.时间(Date.Time.Timestamp) java.sql.Date/java.sql.Time/java.sql.Timestamp extends java.util.Date public class TimeData { PreparedStatement pStatement=null; //操作日期类型的数据 public void insertDate(Connection connection,long time){ try { String sql="insert i

struts2前端页面读取Clob BLOB

在通过Struts2标签显示对象的Clob属性值的时候,显示的并不是CLOB或者BLOB的内容,而是显示的toString方法的值 例如我在实体中的注解为: @Lob @Column(name = "CONTENT_TEXT") public String getContentText() { return contentText; } 前台页面读取方式为: <s:property value="#entry.contentText" /> 显示结果为: