hibernate 快速入门
来源:互联网 发布:全国矢量数据下载 编辑:程序博客网 时间:2024/05/02 00:43
1.学习hibernate最重要的是关系,也就是*.hbm.xml文件的配置,不管struts,hibernate,spring还是标准的web应用,xml文件都是了解框架最直接的方法,它在某些程度上相当与注册表的功能。
2.pojo类(javabean的另一个商业名字),数据库表,他们都可以单独存在单独运行,没有问题。能够把他们有机联合起来的就是*.hbm.xml文件
3.下面来讲关系,我下面的关系都是双向的,这样好理解
3.1一对一
方式1:唯一的外键
<many-to-one unique="true"> (唯一的外键)
<one-to-one>
例子:
public class Address {
private Long id;
private String city;
private Customer customer;
...set/get 方法省略
public class Customer {
private Long id;
private String name;
private Address homeAddress;
...set/get 方法省略
Address.hbm.xml
<hibernate-mapping>
<class name="com.xx.one2one.foreignkey.Address"
table="ADDRESSES">
<id name="id" type="long" column="ID">
<generator class="increment" />
</id>
<property name="city" />
<one-to-one name="customer"
class="com.xx.one2one.foreignkey.Customer"/>
</class>
</hibernate-mapping>
Customer.hbm.xml
<hibernate-mapping >
<class name="com.xx.one2one.foreignkey.Customer">
<id name="id" type="long" column="ID">
<generator class="increment"/>
</id>
<property name="name" />
<many-to-one name="homeAddress"
class="com.xx.one2one.foreignkey.Address"
unique="true"/>
</class>
</hibernate-mapping>
方式2:共享主键
<one-to-one>
<one-to-one constrained="true"> (既是主键又是外键),主键生成方式需要用:foreign
例子:
public class Person {
private int id;
private String name;
private IdCard idCard = new IdCard();
...set/get 方法省略
public class IdCard {
private int id;
private int cardNb;
private Person pp ;
...set/get 方法省略
IdCard.hbm.xml
<hibernate-mapping>
<class name="com.xx.one2one.IdCard">
<id name="id">
<generator class="native" />
</id>
<property name="cardNb"></property>
<one-to-one name="pp" class="com.xx.one2one.Person"></one-to-one>
</class>
</hibernate-mapping>
Person.hbm.xml
<hibernate-mapping>
<class name="com.xx.one2one.Person">
<id name="id">
<generator class="foreign">
<param name="property">idCard</param>
</generator>
</id>
<property name="name"></property>
<one-to-one name="idCard" constrained="true"
class="com.xx.one2one.IdCard">
</one-to-one>
</class>
</hibernate-mapping>
3.2多对一
例子:
public class Dept{
2.pojo类(javabean的另一个商业名字),数据库表,他们都可以单独存在单独运行,没有问题。能够把他们有机联合起来的就是*.hbm.xml文件
3.下面来讲关系,我下面的关系都是双向的,这样好理解
3.1一对一
方式1:唯一的外键
<many-to-one unique="true"> (唯一的外键)
<one-to-one>
例子:
public class Address {
...set/get 方法省略
public class Customer {
...set/get 方法省略
Address.hbm.xml
<hibernate-mapping>
</hibernate-mapping>
Customer.hbm.xml
<hibernate-mapping >
</hibernate-mapping>
方式2:共享主键
<one-to-one>
<one-to-one constrained="true"> (既是主键又是外键),主键生成方式需要用:foreign
例子:
public class Person {
...set/get 方法省略
public class IdCard {
...set/get 方法省略
IdCard.hbm.xml
<hibernate-mapping>
</hibernate-mapping>
Person.hbm.xml
<hibernate-mapping>
</hibernate-mapping>
3.2多对一
例子:
public class Dept{