复合主键
复合主键的意思就是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
<class name="Airle" table="t_airline">
<!-- 复合主键,双主键,数据库start_city,end_city同时为主键 -->
<composite-id>
<key-property name="startCity" column="start_city" length="3" />
<key-property name="endCity" column="end_city" length="3"/>
</composite-id>
<property name="name" />
</class>
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
如果觉得我的文章对您有帮助,请予以打赏。您的支持将鼓励我继续创作!谢谢!