Hibernate 菜鸟教程 8 复合主键

复合主键

复合主键的意思就是2个字段同时为主键
不使用无业务含义的自增id作为主键

模型对象Airline

package com.jege.hibernate.compositeid;

import java.io.Serializable;

//使用复合主键的持久化类需要实现serializable接口和覆盖equals()、hashCode()方法。
public class Airline implements Serializable{
    private String startCity;
    private String endCity; 
    private String name;
    public String getStartCity() {
        return startCity;
    }
    public void setStartCity(String startCity) {
        this.startCity = startCity;
    }
    public String getEndCity() {
        return endCity;
    }
    public void setEndCity(String endCity) {
        this.endCity = endCity;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((endCity == null) ? 0 : endCity.hashCode());
        result = prime * result
                + ((startCity == null) ? 0 : startCity.hashCode());
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Airline other = (Airline) obj;
        if (endCity == null) {
            if (other.endCity != null)
                return false;
        } else if (!endCity.equals(other.endCity))
            return false;
        if (startCity == null) {
            if (other.startCity != null)
                return false;
        } else if (!startCity.equals(other.startCity))
            return false;
        return true;
    }
}

映射文件Airline.hbm.xml


        
        
            
            
        
        
    

测试类MainTest

public class MainTest {
  Session session = null;

  @Before
  public void save() {
    session = HibernateUtils.INSTANCE.getSession();
    session.beginTransaction();
    Airline airline = new Airline();
    airline.setStartCity("PEK");
    airline.setEndCity("SHA");
    airline.setName("北京飞上海");
    session.save(airline);
  }

  @Test
  public void get() {
    Airline id = new Airline();
    id.setStartCity("PEK");
    id.setEndCity("SHA");

    Airline target = (Airline) session.get(Airline.class, id);
    System.out.println(target.getName());

  }

  @After
  public void colse() {
    session.getTransaction().commit();
    session.close();
  }
}

源码地址

https://github.com/je-ge/hibernate

如果觉得我的文章或者代码对您有帮助,可以请我喝杯咖啡。
**您的支持将鼓励我继续创作!谢谢! **

Hibernate 菜鸟教程 8 复合主键_第1张图片
微信打赏

Hibernate 菜鸟教程 8 复合主键_第2张图片
支付宝打赏

你可能感兴趣的:(Hibernate 菜鸟教程 8 复合主键)