日期:2014-05-16 浏览次数:20420 次
对象表映射
?
实体类--数据库表间的转换
?
由于Hibernate的存储都是建立在对象基础上的,所以映射好实体类对象和数据库表是非常重要的,数据库表的设计也必须按照一定的规范来(冗余字段等就不允许存在?)
?
本章的目录:
1.简单对象表映射
--搭建JUnit测试环境
?
?
?
?
附:
搭建JUnit测试环境
1.去官网下载jar包
2.解压,复制junit-4.10.jar(我用的此时是4.10版本)到bin下的jar中
3.在项目名上右键→new→Source Folder→输入名称→finish
4.注意,你对哪个包进行测试,你就在测试下建立和那个包相同的包
5.建立测试类,需要在测试的方法前面加入”@Test”
?
?
1.简单对象表映射,(单表无关联)
先把实体类贴出来(本人英文名jake,无需吐槽包名)
?
package com.jake.hibernate.domain; import java.util.Date; public class Person { private long id; private String name; private Date birthday; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } }?
?
然后是映射文件:建议与实体类同包,名字为 ? 实体类名.hbm.xml
?
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.jake.hibernate.domain"> <class name="Person" table="PERSON"> <id name="id" column="id"> <generator class="native" /> </id> <property name="name" column="name" /> <property name="birthday" type="timestamp" column="birthday" /> </class> </hibernate-mapping>
?
?然后是配置文件(参考文档中给的)
?
<?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost:3306/hibernateTest</property> <property name="connection.username">root</property> <property name="connection.password">123456</property> <!-- JDBC connection pool (use the built-in) --> <property name="connection.pool_size">10</property> <!-- SQL dialect --> <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property> <!-- Enable Hibernate's automatic session context management --> <property name="current_session_context_class">thread</property> <!-- Disable the second-level cache --> <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property> <!-- Echo all executed SQL to stdout --> <property name="show_sql">true</property> <!-- Drop and re-create the database schema on startup --> <property name="hbm2ddl.auto">update</property> <property name="show_sql">true</property> <property name="format_sql">true</property> <mapping resource="com/jake/hibernate/domain/Person.hbm.xml" /> <!-- <mapping resource="org/hibernate/tutorial/doma