1. 项目结构
2. 三个持久化类
① Pay.java
package com.baidu.cfghbm; public class Pay { //月薪 private Integer monthlyPay; //年薪 private Integer yearPay; //带薪假 private Integer vocationWithPay; // private Worker worker; public Worker getWorker() { return worker; } public void setWorker(Worker worker) { this.worker = worker; } public Integer getMonthlyPay() { return monthlyPay; } public void setMonthlyPay(Integer monthlyPay) { this.monthlyPay = monthlyPay; } public Integer getYearPay() { return yearPay; } public void setYearPay(Integer yearPay) { this.yearPay = yearPay; } public Integer getVocationWithPay() { return vocationWithPay; } public void setVocationWithPay(Integer vocationWithPay) { this.vocationWithPay = vocationWithPay; } }
② Person.java
package com.baidu.cfghbm; import java.sql.Blob; import java.util.Date; public class Person { private Integer id; private String name; private String shiYan; public String getShiYan() { return shiYan; } public void setShiYan(String shiYan) { this.shiYan = shiYan; } private String interest; private Date birth; //该属性的值为:name :birth private String desc; //映射长文本 private String content; //映射二进制 private Blob image; public Person() { super(); } public Person(String name, String interest, Date birth) { super(); this.name = name; this.interest = interest; this.birth = birth; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Blob getImage() { return image; } public void setImage(Blob image) { this.image = image; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getInterest() { return interest; } public void setInterest(String interest) { this.interest = interest; } public Date getBirth() { return birth; } public void setBirth(Date birth) { this.birth = birth; } }
package com.baidu.cfghbm; public class Worker { private Integer id; private String name; private Pay pay; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Pay getPay() { return pay; } public void setPay(Pay pay) { this.pay = pay; } }
① Person.hbm.xml
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Generated 2016-5-17 14:39:37 by Hibernate Tools 3.4.0.CR1 --> <hibernate-mapping package="com.baidu.cfghbm"> <class name="Person" table="PERSON" dynamic-update="true"> <id name="id" type="java.lang.Integer"> <column name="ID" /> <generator class="native" /> </id> <property name="name" type="java.lang.String" column="NAME" length="30" > </property> <property name="shiYan" type="java.lang.String" unique="true" update="false" index="person_index" length="20" > <!-- name: 指定该持久化类的属性的名字 column: 指定与类的属性映射的表的字段名. 如果没有设置该属性, Hibernate 将直接使用类的属性名作为字段名. type: 指定 Hibernate 映射类型. Hibernate 映射类型是 Java 类型与 SQL 类型的桥梁. 如果没有为某个属性显式设定映射类型, Hibernate 会运用反射机制先识别出持久化类的特定属性的 Java 类型, 然后自动使用与之对应的默认的 Hibernate 映射类型. unique: 设置是否为该属性所映射的数据列添加唯一约束. access: 指定 Hibernate 的默认的属性访问策略。默认值为 property, 即使用 getter, setter 方法来访问属性. 若指定 field, 则 Hibernate 会忽略 getter/setter 方法, 而通过反射访问成员变量 not-null:若该属性值为 true, 表明不允许为 null, 默认为 false update: 设置为 false ,表示不允许被修改,true表示可以被修改 index: 指定一个字符串的索引名称. 当系统需要 Hibernate 自动建表时, 用于为该属性所映射的数据列创建索引, 从而加快该数据列的查询. scale: 指定该属性所映射数据列的小数位数, 对 double, float, decimal 等类型的数据列有效. formula:设置一个 SQL 表达式, Hibernate 将根据它来计算出派生属性的值. 派生属性: 并不是持久化类的所有属性都直接和表的字段匹配, 持久化类的有些属性的值必须在运行时通过计算才能得出来, 这种属性称为派生属性 使用 formula 属性时 formula=“(sql)” 的英文括号不能少 Sql 表达式中的列名和表名都应该和数据库对应, 而不是和持久化对象的属性对应 如果需要在 formula 属性中使用参数, 这直接使用 where cur.id=id 形式, 其中 id 就是参数, 和当前持久化对象的 id 属性对应的列的 id 值将作为参数传入. length: 指定该属性所映射数据列的字段的长度 小细节: 如果你想让映射文件在数据库中创建的的 字段是length设置的值的话, 必须要包column属性配置到property 中,否则不会成length设置不会成功。 示例如下: <property name="shiYan" type="java.lang.String" column="SHI_YAN" length="20"></property> --> <column name="SHI_YAN"></column> </property> <property name="interest" type="java.lang.String"> <column name="INTEREST" /> </property> <property name="birth" type="time" index="person_index"> <column name="BIRTH" /> </property> <!-- 映射派送属性 --> <property name="desc" formula="(SELECT concat(name,':',birth) FROM PERSON p WHERE p.id = id)"></property> <!-- 映射大对象 <property name="content" type="clob"></property> 下面的反射是精确映射content 类型 --> <property name="content"> <column name="CONTENT" sql-type="mediumtext"></column> </property> <!-- 映射二进制 <property name="image" type="blob"></property> 下面的方式是精确映射image 的类型 --> <property name="image" type="blob"> <column name="IMAGE" sql-type="mediumblob" /> </property> </class> </hibernate-mapping>
② . Worker.hbm.xml
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.baidu.cfghbm"> <class name="Worker" table="WORKER"> <id name="id" type="java.lang.Integer"> <column name="ID" /> <generator class="native" /> </id> <property name="name" type="java.lang.String"> <column name="NAME" /> </property> <!-- 映射组成关系 --> <component name="pay"> <!-- parent: 指定组件属性所属的整体类 前提是把要Worker 写道pay 中 name :整体类在组件类中的属性名 --> <parent name="worker"/> <!-- 指定组成关系的组件的属性 --> <property name="monthlyPay" column="MONTHLY_PAY"></property> <property name="yearPay" column="YEAR_PAY"></property> <property name="vocationWithPay" column="VOCATION_WITH_PAY"></property> </component> </class> </hibernate-mapping>
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- 配置连接数据库的基本信息 --> <property name="connection.username">root</property> <property name="connection.password">chuck</property> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql:///hibernate</property> <!-- 配置hibernate 的基本信息 --> <!-- hibernate 所使用的数据库方言 --> <property name="dialect">org.hibernate.dialect.MySQLInnoDBDialect</property> <!-- 执行操作时是否在控制台打印SQL --> <property name="show_sql">true</property> <!-- 是否对SQL格式 --> <property name="format_sql">true</property> <!-- 指定自动生成数据表的策略 --> <property name="hbm2ddl.auto">update</property> <!-- 设置Hibernate 的事务隔离级别--> <property name="hibernate.connection.isolation">2</property> <!-- 删除对象后,使其OID 置为null--> <property name="use_identifier_rollback">true</property> <!-- 配置c3p0 数据源--> <!-- 数据库最大连接数--> <property name="hibernate.c3p0.max_size">30</property> <!-- 数据库最小连接数--> <property name="hibernate.c3p0.min_size">5</property> <!-- 当数据库连接耗尽时,每次获取新的连接数--> <property name="hibernate.c3p0.acquire_increment">5</property> <!-- 检测线程每次检测所有连接对象是否超时的时间间隔--> <property name="hibernate.c3p0.idle_test_period">2000</property> <!-- 数据库连接池中连接对象多久没使用连接,就应该销毁连接--> <property name="hibernate.c3p0.timeout">2000</property> <!--缓存Statement 对象的数量 --> <property name="hibernate.c3p0.max_statements">10</property> <!-- 下面两条批量操作的设置 对mysql 是无效的 ,但是对Oracle 是有效的 --> <!-- 设置JDBC 的 Statement 读取数据的时候,每次从数据库中取出的记录条数 --> <property name="hibernate.jdbc.factory_class">100</property> <!-- 设置对 数据库进行批量删除,批量更新和批量插入的时候的批次大小 --> <property name="hibernate.jdbc.batch_size">30</property> <!-- 指定关联的 .hbm.xml 文件 --> <mapping resource="com/baidu/cfghbm/Person.hbm.xml" /> <mapping resource="com/baidu/cfghbm/Worker.hbm.xml" /> <!-- 其他的配置项参考:hibernate-release-4.2.4.Final/documentation/manual/en-US/html_single/index.html --> </session-factory> </hibernate-configuration>
~~~~~~~~~~~~~~~~~~~~~~~~~分割线~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
package com.baidu.cfghbm; import java.io.IOException; import java.io.InputStream; import java.sql.Blob; import java.sql.Connection; import java.sql.SQLException; import java.util.Date; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.hibernate.jdbc.Work; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; import org.junit.After; import org.junit.Before; import org.junit.Test; public class TestCfg { private SessionFactory sessionFactory; private Session session; private Transaction transaction; @Before public void init(){ Configuration configuration = new Configuration().configure(); ServiceRegistry serviceRegistry = new ServiceRegistryBuilder() .applySettings(configuration.getProperties()) .buildServiceRegistry(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); session = sessionFactory.openSession(); transaction = session.beginTransaction(); } @After public void destroy(){ transaction.commit(); session.close(); sessionFactory.close(); } @Test public void testComponent(){ Worker worker = new Worker(); Pay pay = new Pay(); pay.setMonthlyPay(10000); pay.setYearPay(150000); pay.setVocationWithPay(5); worker.setName("shoping"); worker.setPay(pay); session.save(worker); } /** * 对Blob 的读写 * * */ @Test public void testBlob() throws IOException, SQLException{ //保存Blob 对象 // Person person = new Person(); // person.setName("AA"); // person.setInterest("sport");; // person.setBirth(new Date());; // person.setDesc("DESC"); // person.setContent("I love java!"); // // InputStream stream = new FileInputStream("image.PNG"); // Blob image = Hibernate.getLobCreator(session) // .createBlob(stream, stream.available()); // person.setImage(image);; // // session.save(person); //获取 Blob 对象 Person person = (Person) session.get(Person.class, 1); Blob image = person.getImage(); InputStream in = image.getBinaryStream(); System.out.println(in.available()); } @Test public void testPropertyUpdate(){ Person person = (Person) session.get(Person.class, 1); person.setName("Tom"); System.out.println(person.getBirth()); } @Test public void testIdGenerator() throws InterruptedException{ Person person = new Person("Tom", "music", new Date()); session.save(person); //Thread.sleep(5000); } @Test public void testDynamicUpdate(){ Person person = (Person) session.get(Person.class, 1); person.setName("WangXiang"); person.setBirth(new Date()); } @Test public void testDowork() { session.doWork(new Work(){ @Override public void execute(Connection connection) throws SQLException { System.out.println(connection); } }); } }