`

Hibernate之---复合主键

阅读更多
转载:http://hi.baidu.com/javajavajava/blog
数据库脚本:

create table people(
name varchar(100) not null,
phone varchar(50) not null,
age int,
primary key(name,phone)
);

一、不把复合主键封装成类

hibernate.cfg.xml
<?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">

<!-- Generated by MyEclipse Hibernate Tools.                     -->
<hibernate-configuration>
<session-factory>
<property name="connection.username">sa</property>
<property name="connection.url">
   jdbc:microsoft:sqlserver://localhost:1433
</property>
<property name="dialect">
    org.hibernate.dialect.SQLServerDialect
</property>
<property name="myeclipse.connection.profile">sql2000</property>
<property name="connection.password">sa</property>
<property name="connection.driver_class">
    com.microsoft.jdbc.sqlserver.SQLServerDriver
</property>
<property name="show_sql">true</property>
<mapping resource="org/myhibernate/demo02/People.hbm.xml" />
</session-factory>
</hibernate-configuration>

People.hbm.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- 
      Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
      <class name="org.myhibernate.demo02.People" table="people" schema="dbo" catalog="mldn">
         <composite-id>
             <key-property name="name" type="java.lang.String">
                  <column name="name" length="100" />
             </key-property>
             <key-property name="phone" type="java.lang.String">
                  <column name="phone" length="50" />
             </key-property>
         </composite-id>
          <property name="age" type="java.lang.Integer">
              <column name="age" />
          </property>
      </class>
</hibernate-mapping>

People.kava 

package org.myhibernate.demo02;

import java.io.Serializable;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;

public class People implements Serializable {

private String name;

private String phone;

private int age;

@Override //此处使用到了Apache的开源工具包commons-lang-2.3.jar 复写equals和hashCode方法
public boolean equals(Object obj) {
    if (this == obj) {
     return true;
    }
    if (!(obj instanceof People)) {
     return false;
    }
    People p = (People) obj;
    return new EqualsBuilder().append(this.name, p.name).append(this.phone,
      p.phone).append(this.age, p.age).isEquals();
}

@Override
public int hashCode() {

    return new HashCodeBuilder().append(this.name).append(this.phone)
      .append(this.age).toHashCode();
}

public int getAge() {
    return age;
}

public void setAge(int age) {
    this.age = age;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getPhone() {
    return phone;
}

public void setPhone(String phone) {
    this.phone = phone;
}

}


PeopleDAO.java

package org.myhibernate.demo02;

import org.hibernate.Session;
import org.hibernate.cfg.Configuration;

public class PeopleDAO {

private Session session;

public PeopleDAO() {
    this.session = new Configuration().configure().buildSessionFactory()
      .openSession();
}

public void insert(People p){
    this.session.save(p);
    this.session.beginTransaction().commit();
}
}


Test.java(测试文件)

package org.myhibernate.demo02;

public class Test {

/**
    * @param args
    */
public static void main(String[] args) {
    People p = new People();
    PeopleDAO pdao = new PeopleDAO();
  
    p.setName("咖啡迷");
    p.setPhone("8888888");
    p.setAge(23);
  
    pdao.insert(p);
}

}

二、把复合主键封装成类

hibernate.cfg.xml
<?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">

<!-- Generated by MyEclipse Hibernate Tools.                     -->
<hibernate-configuration>

<session-factory>
<property name="connection.username">sa</property>
<property name="connection.url">
    jdbc:microsoft:sqlserver://localhost:1433
</property>
<property name="dialect">
    org.hibernate.dialect.SQLServerDialect
</property>
<property name="myeclipse.connection.profile">sql2000</property>
<property name="connection.password">sa</property>
<property name="connection.driver_class">
    com.microsoft.jdbc.sqlserver.SQLServerDriver
</property>
<property name="show_sql">true</property>
<mapping resource="org/myhibernate/demo03/People.hbm.xml" />
</session-factory>
</hibernate-configuration>

People.hbm.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- 
      Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
      <class name="org.myhibernate.demo03.People" table="people" schema="dbo" catalog="mldn">
          <composite-id name="id" class="org.myhibernate.demo03.PeopleId">
              <key-property name="name" type="java.lang.String">
                  <column name="name" length="100" />
             </key-property>
              <key-property name="phone" type="java.lang.String">
                  <column name="phone" length="50" />
              </key-property>
          </composite-id>
          <property name="age" type="java.lang.Integer">
              <column name="age" />
          </property>
      </class>
</hibernate-mapping>

People.java

package org.myhibernate.demo03;

/**
* People generated by MyEclipse Persistence Tools
*/

public class People implements java.io.Serializable {

// Fields

private PeopleId id;

private Integer age;

// Constructors

/** default constructor */
public People() {
}

/** minimal constructor */
public People(PeopleId id) {
    this.id = id;
}

/** full constructor */
public People(PeopleId id, Integer age) {
    this.id = id;
    this.age = age;
}

// Property accessors

public PeopleId getId() {
    return this.id;
}

public void setId(PeopleId id) {
    this.id = id;
}

public Integer getAge() {
    return this.age;
}

public void setAge(Integer age) {
    this.age = age;
}

}


PeopleId.java

package org.myhibernate.demo03;

/**
* PeopleId generated by MyEclipse Persistence Tools
*/

public class PeopleId implements java.io.Serializable {

// Fields

private String name;

private String phone;

// Constructors

/** default constructor */
public PeopleId() {
}

/** full constructor */
public PeopleId(String name, String phone) {
    this.name = name;
    this.phone = phone;
}

// Property accessors

public String getName() {
    return this.name;
}

public void setName(String name) {
    this.name = name;
}

public String getPhone() {
    return this.phone;
}

public void setPhone(String phone) {
    this.phone = phone;
}

public boolean equals(Object other) {
    if ((this == other))
     return true;
    if ((other == null))
     return false;
    if (!(other instanceof PeopleId))
     return false;
    PeopleId castOther = (PeopleId) other;

    return ((this.getName() == castOther.getName()) || (this.getName() != null
      && castOther.getName() != null && this.getName().equals(
      castOther.getName())))
      && ((this.getPhone() == castOther.getPhone()) || (this
        .getPhone() != null
        && castOther.getPhone() != null && this.getPhone()
        .equals(castOther.getPhone())));
}

public int hashCode() {
    int result = 17;

    result = 37 * result
      + (getName() == null ? 0 : this.getName().hashCode());
    result = 37 * result
      + (getPhone() == null ? 0 : this.getPhone().hashCode());
    return result;
}

}

PeopleDAO.java

package org.myhibernate.demo03;

import org.hibernate.Session;
import org.hibernate.cfg.Configuration;

public class PeopleDAO {

private Session session;

public PeopleDAO() {
    this.session = new Configuration().configure().buildSessionFactory()
      .openSession();
}

public void insert(People p){
    this.session.save(p);
    this.session.beginTransaction().commit();
}
}


Test.java(测试文件)

package org.myhibernate.demo03;

public class Test {

/**
    * @param args
    */
public static void main(String[] args) {
    People p = new People();
    PeopleId id = new PeopleId();
    PeopleDAO pdao = new PeopleDAO();
  
    id.setName("hi.baidu.com/javajavajava");
    id.setPhone("8888888");
  
    p.setId(id);
    p.setAge(23);
  
    pdao.insert(p);
}
}


分享到:
评论

相关推荐

    hibernate复合主键配置和使用

    《Hibernate复合主键配置与使用详解》 在Java开发中,Hibernate作为一款强大的ORM框架,大大简化了数据库操作。然而,当我们面临复杂的数据表结构,尤其是涉及到复合主键时,如何在Hibernate中进行配置和使用就显得...

    Hibernate复合主键

    "Hibernate复合主键" Hibernate复合主键是指在 Hibernate 框架中使用复合主键来唯一标识一个实体。复合主键是指由多个字段组成的主键,用于唯一标识一个实体。在本例中,我们将通过一个简单的复合主键的做关联类的...

    hibernate 无主键表映射

    通过以上的解释,我们可以看到,虽然无主键表在数据库中并不常见,但在某些特定场景下,如复合主键,Hibernate提供了一套完整的解决方案。所提供的资源包括一个简单的Demo,可以实际运行并理解无主键表映射的实现...

    hibernate复合主键设置

    在Java的持久化框架Hibernate中,复合主键(Composite Key)是一种特殊的数据结构,用于处理具有多个字段作为唯一标识的情况。本教程将深入探讨如何在Hibernate中设置复合主键,并提供一个可直接使用的配置示例。 ...

    hibernate-annotations-3.4.0.GA

    4. 新的持久化模型:支持复合主键、级联操作等更复杂的持久化模型。 5. 可配置的延迟加载:通过注解可以控制属性或关联关系的延迟加载行为。 四、实战应用 1. 创建实体类:利用@Entity、@Table、@Id等注解创建符合...

    hibernate复合主键映射

    在Java的持久化框架Hibernate中,复合主键(Composite Key)是一种特殊的数据模型,它用于表示由多个属性共同构成的唯一标识。这种设计通常出现在实体类的某些属性组合起来才能唯一确定一个对象的情况下。本篇文章将...

    hibernate-annotations-3.4.0.GA.rar

    - `@Embeddable`: 标记一个类为可嵌入的,这个类的实例可以作为其他类的复合主键的一部分。 10. **缓存配置** - `@Cacheable`: 开启实体的缓存支持,提高数据读取速度。 - `@Cache`: 配置缓存区域和策略,如READ...

    hibernate复合主键的实例

    当一个表的主键由两个或更多个字段组成时,我们称之为复合主键。复合主键确保了这些字段组合的唯一性,而单个字段可能不是唯一的。 二、为什么要使用复合主键? 在某些情况下,单一字段无法唯一标识表中的记录,...

    HIBERNATE - 符合Java习惯的关系数据库持久化

    3. **复合主键**:当需要使用多个字段作为主键时,可以使用composite-id元素。 4. **继承映射**:支持多种继承映射策略,如单表(Single Table)、类表(Class Table)、子表(Subclass Table)等。 5. **属性映射**...

    Hibernate复合主键.

    本篇文章将深入探讨Hibernate如何支持和管理复合主键。 一、理解复合主键 在数据库设计中,复合主键是一种特殊情况,当单个字段不能唯一标识表中的每一行时,可以使用两个或多个字段的组合来创建唯一的标识。例如...

    Hibernate复合主键视频2

    请更名为 Hibernate复合主键.part2.rar

    Hibernate复合主键3

    更名为 Hibernate复合主键.part3.rar

    hibernate_-annotations_中文帮助文档api完整版

    - **映射复合主键与外键**:使用`@IdClass`或`@EmbeddedId`映射复合主键。 - **映射二级表**:使用`@SecondaryTables`映射多个表来支持实体。 #### 四、映射查询 - **映射EJBQL/HQL查询**:使用`@NamedQuery`注解...

    Hibernate复合主键part1

    本章讲解Hibernate中对数据库复合主键的支持

    hibernate_-annotations_中文帮助文档.doc

    - **复合主键与外键**:使用`@IdClass`和`@JoinColumn`等注解处理复杂主键和外键情况。 - **二级表映射**:`@SecondaryTable`注解用于映射实体到多个表。 4. **Hibernate独有的注解扩展** - **实体、标识符、...

Global site tag (gtag.js) - Google Analytics