1.通常将复合主键单独建一个类;
2.复合主键类必须实现java.io.Serializable接口,必须重写hashCode和 equals方法;
3.在映射文件中配置复合主键:
<composite-id name="复合主键类名"& gt;
<key-property name="复合主键属性1" column="对应字段名" />
<key- property name="复合主键属性2" column="对应字段名" />
</composite-id>
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">scott</property>
<property name="connection.url">
jdbc:oracle:thin:@127.0.0.1:1521:MGC
</property>
<property name="dialect">
org.hibernate.dialect.Oracle9Dialect
</property>
<property name="myeclipse.connection.profile">MGC</property>
<property name="connection.password">tiger</property>
<property name="connection.driver_class">
oracle.jdbc.driver.OracleDriver
</property>
<property name="show_sql">true</property>
<mapping
resource="cn/edu/ahau/mgc/hibernate/pojo/YearPeriod.hbm.xml" />
</session-factory>
</hibernate-configuration>
YearPeriodPK.java:
package cn.edu.ahau.mgc.hibernate.pojo;
import java.io.Serializable;
public class YearPeriodPK implements Serializable{
private int year;
private int period;
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getPeriod() {
return period;
}
public void setPeriod(int period) {
this.period = period;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + period;
result = prime * result + year;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final YearPeriodPK other = (YearPeriodPK) obj;
if (period != other.period)
return false;
if (year != other.year)
return false;
return true;
}
}
YearPeriod.java:
package cn.edu.ahau.mgc.hibernate.pojo;
import java.util.Calendar;
public class YearPeriod {
private YearPeriodPK yearPeriodPK;
private Calendar beginDate;
private Calendar endDate;
public YearPeriodPK getYearPeriodPK() {
return yearPeriodPK;
}
public void setYearPeriodPK(YearPeriodPK yearPeriodPK) {
this.yearPeriodPK = yearPeriodPK;
}
public Calendar getBeginDate() {
return beginDate;
}
public void setBeginDate(Calendar beginDate) {
this.beginDate = beginDate;
}
public Calendar getEndDate() {
return endDate;
}
public void setEndDate(Calendar endDate) {
this.endDate = endDate;
}
}
YearPeriod.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="cn.edu.ahau.mgc.hibernate.pojo.YearPeriod" table="YEARPERIOD" schema="SCOTT">
<composite-id name="YearPeriodPK">
<key-property name="year" column="YEAR" />
<key-property name="Period" column="PERIOD" />
</composite-id>
<property name="beginDate" type="java.util.Calendar" column="BEGINDATE" />
<property name="endDate" type="java.util.Calendar" column="ENDDATE" />
</class>
</hibernate-mapping>
HibernateSessionFactory.java:
package cn.edu.ahau.mgc.hibernate.many2one.factory;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
/**
* Configures and provides access to Hibernate sessions, tied to the
* current thread of execution. Follows the Thread Local Session
* pattern, see {@link http://hibernate.org/42.html }.
*/
public class HibernateSessionFactory {
/**
* Location of hibernate.cfg.xml file.
* Location should be on the classpath as Hibernate uses
* #resourceAsStream style lookup for its configuration file.
* The default classpath location of the hibernate config file is
* in the default package. Use #setConfigFile() to update
* the location of the configuration file for the current session.
*/
private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static Configuration configuration = new Configuration();
private static org.hibernate.SessionFactory sessionFactory;
private static String configFile = CONFIG_FILE_LOCATION;
static {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private HibernateSessionFactory() {
}
/**
* Returns the ThreadLocal Session instance. Lazy initialize
* the SessionFactory if needed.
*
* @return Session
* @throws HibernateException
*/
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
}
return session;
}
/**
* Rebuild hibernate session factory
*
*/
public static void rebuildSessionFactory() {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
/**
* Close the single hibernate session instance.
*
* @throws HibernateException
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
/**
* return session factory
*
*/
public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
}
/**
* return session factory
*
* session factory will be rebuilded in the next call
*/
public static void setConfigFile(String configFile) {
HibernateSessionFactory.configFile = configFile;
sessionFactory = null;
}
/**
* return hibernate configuration
*
*/
public static Configuration getConfiguration() {
return configuration;
}
}
ExportToDBCreate.java:
package cn.edu.ahau.mgc.hibernate.export;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
public class ExportToDBCreate {
public static void main(String[] args) {
Configuration cfg = new Configuration().configure();
SchemaExport export = new SchemaExport(cfg);
export.create(true, true);
}
}
InitData.java:
package cn.edu.ahau.mgc.hibernate.export;
import java.util.Calendar;
import org.hibernate.Session;
import cn.edu.ahau.mgc.hibernate.factory.HibernateSessionFactory;
import cn.edu.ahau.mgc.hibernate.pojo.YearPeriod;
import cn.edu.ahau.mgc.hibernate.pojo.YearPeriodPK;
public class InitData {
public static void main(String[] args) {
Session session = null;
try {
session = HibernateSessionFactory.getSession();
session.beginTransaction();
YearPeriodPK yearPeriodPK = new YearPeriodPK();
yearPeriodPK.setYear(2008);
yearPeriodPK.setPeriod(1);
YearPeriod yearPeriod = new YearPeriod();
yearPeriod.setYearPeriodPK(yearPeriodPK);
Calendar beginDate = Calendar.getInstance();
beginDate.set(2008, 2, 1);
Calendar endDate = Calendar.getInstance();
endDate.set(2008, 6, 1);
yearPeriod.setBeginDate(beginDate);
yearPeriod.setEndDate(endDate);
session.save(yearPeriod);
session.getTransaction().commit();
} catch (Exception e) {
session.getTransaction().rollback();
e.printStackTrace();
} finally {
HibernateSessionFactory.closeSession();
}
}
}
LoadData.java:
package cn.edu.ahau.mgc.hibernate.export;
import java.text.SimpleDateFormat;
import org.hibernate.Session;
import cn.edu.ahau.mgc.hibernate.factory.HibernateSessionFactory;
import cn.edu.ahau.mgc.hibernate.pojo.YearPeriod;
import cn.edu.ahau.mgc.hibernate.pojo.YearPeriodPK;
public class LoadData {
public static void main(String[] args) {
Session session = null;
try {
session = HibernateSessionFactory.getSession();
YearPeriodPK yearPeriodPK = new YearPeriodPK();
yearPeriodPK.setYear(2008);
yearPeriodPK.setPeriod(1);
YearPeriod yearPeriod = (YearPeriod) session.load(YearPeriod.class, yearPeriodPK);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("Begin Date:" + sdf.format(yearPeriod.getBeginDate().getTime()));
System.out.println("End Date:" + sdf.format(yearPeriod.getEndDate().getTime()));
} catch (Exception e) {
e.printStackTrace();
} finally {
HibernateSessionFactory.closeSession();
}
}
}