示例:
Person类,定义了各种属性:
package com.suo.domain;
import java.sql.Date;
public class Person {
private Long id;
private String username;
private String password;
private int telphone;
private char gender;
private boolean graduation;
private Date birthday;
private Timestamp marryTime;
private byte[] file;
……//set/get方法
}
映射文件:
<hibernate-mapping package="com.suo.domain">
<class name="Person">
<id name="id" column="id" type="long">
<generator class="native"/>
</id>
<property name="username" column="username" type="string"/>
<property name="password" column="password" type="string"/>
<property name="telphone" column="telphone" type="int"/>
<property name="gender" column="gender" type="character"/>
<property name="graduation" column="graduation" type="boolean"/>
<property name="birthday" column="birthday" type="date"/>
<property name="marryTime" column="marryTime" type="timestamp"/>
<property name="file" column="file" type="binary"/>
</class>
</hibernate-mapping>
数据库:
CREATE TABLE `person` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`username` varchar(255) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
`telphone` int(11) DEFAULT NULL,
`gender` char(1) DEFAULT NULL,
`graduation` bit(1) DEFAULT NULL,
`birthday` date DEFAULT NULL,
`marryTime` timestamp NULL DEFAULT NULL,
`file` mediumblob,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=gbk
测试:
package com.suo.test;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Timestamp;
import java.util.Iterator;
import java.util.List;
import com.suo.dao.PersonDAO;
import com.suo.dao.impl.PersonDAOImpl;
import com.suo.domain.Person;
public class Test {
public static void main(String[] args) throws IOException {
Person person=new Person();
person.setUsername("suo");
person.setPassword("123");
person.setBirthday(new java.sql.Date(new java.util.Date().getTime()));
person.setGender('F');
person.setTelphone(152008);
person.setGraduation(false);
person.setMarryTime(new Timestamp(new java.util.Date().getTime()));
//这里上次的文件较大的话,在数据库中要使用mediumblob数据类型,并且在mysql的my.ini配置文件中配置一下
//max_allowed_packet这个量的值。
InputStream in=new FileInputStream("D:/亲爱的老婆/dai.JPG");
int length=in.available();
byte[] buffer=new byte[length];
in.read(buffer);
in.close();
person.setFile(buffer);
PersonDAO dao=new PersonDAOImpl();
dao.savePerson(person);
List<Person> list=dao.listAllPersons();
for(Iterator<Person> iter=list.iterator(); iter.hasNext();){
Person p = iter.next();
System.out.println(p.getUsername());
System.out.println(p.getPassword());
System.out.println(p.getGender());
System.out.println(p.getTelphone());
System.out.println(p.getBirthday());
System.out.println(p.getMarryTime());
System.out.println(p.isGraduation());
byte[] buff=p.getFile();
OutputStream out=new FileOutputStream("D:/temp/"+p.getId()+".jpg");
out.write(buff);
out.close();
}
PersonDAO dao=new PersonDAOImpl();
dao.removeAll();
}
}