何为关系,何为映射,关系这个词想必大家都不陌生,比如你和老师之间是师生关系,你和父母之间是父子或者父女(母子或者母女关系)。
关系是存在某种联系物体之间产生的,什么都是可能的,比如你和工具,你只能使用工具,但是工具不能使用你,这样的关系是单向的,但是换种说法,你拥有工具,工具也属于你,那么这种关系就是双向的了,此外一个人可以拥有多个工具,并且多个工具也可以是属于一个人的,还有就是多个人拥有多个工具,并且多个工具也属于人,根据这些特征,我们将关系分为以下几种:
单向关系:
one2one,(一对一)
many3one(多对一)
one2many(一对多)
many2many(多对多)
双向关系:
one2many(一对多)
many2many(多对多)
one2one(一对一)
基本映射必备知识
必须存在的文件和实体
实体类(.java)
实体类的存在是基础,因为我们要做的就是将实体类映射成为表,在映射之前先建好实体类,以及主键和各个属性字段。代码如下图:
import java.util.Date;
public class User {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
映射文件(*.hbm.xml)
映射文件通常是以.hbm.xml为后缀的,比如我们建立一个User的实体,那么我们的映射文件就是User.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>
<class name="com.bjpowernode.hibernate.User">
<id name="id">
<generator class="uuid"/>
</id>
<property name="name"/>
<property name="password"/>
</class>
</hibernate-mapping>
Hibernate的配置文件(hibernate.cfg.xml)
当我们建立了实体和映射文件后,下面我们就该进行在配置文件中进行配置了,因为配置文件是我们拿到整个接口和方法的入口,所以在此配置尤为重要。
<!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="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_session</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">bjpowernode</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">true</property>
<mapping resource="com/bjpowernode/hibernate/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
这里不仅仅配置了数据库的信息,并且也配置了映射文件,从而可以通过工具类将映射文件导入到数据库。
工具类
这是我们自己手写的工具类,用于将实体类映射成表,并保存到数据库。
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
/**
* 将hbm生成ddl
* @author Administrator
*
*/
public class ExportDB {
public static void main(String[] args) {
//默认读取hibernate.cfg.xml文件
Configuration cfg = new Configuration().configure();
SchemaExport export = new SchemaExport(cfg);
export.create(true, true);
}
}
小结
了解了上面的基本信息,那就便于我们对于hibernate的七种映射关系进行理解,下面的文章将进行hibernate七种关系的一一讲解。