在Hibernate中,有三种方式实现java中的继承,本文讲一个方法:每个类一张表。
java是面向对象的编程语言。 继承是其中重要的概念。关系模型能实现“是一个”和“有一个"关系。Hibernate给我们提供了类继承的方法。
比如我们有下面的类:shape是基类,circle和rectangle继承了shape.我们将为这3个类生成3张表。
三个类:
三张表:
package org.arpit.javapostsforlearning;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Table;
@Entity
@Table(name="SHAPE")
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public class Shape {
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
@Column(name="Shape_Id")
int shapeId;
@Column(name="Shape_Name")
String shapeName;
public Shape()
{
}
public Shape(String shapeName)
{
this.shapeName=shapeName;
}
//getters and setters
}
为在hibernate中实现继承,要用@Inheritance.它为实现实体类的层次结构,它定义了继承策略。我们在此使用的是Table_Per_Class继承策略。
package org.arpit.javapostsforlearning;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
@Entity
@Table(name="RECTANGLE")
public class Rectangle extends Shape{
@Column(name="Rectangle_Length")
int length;
@Column(name="Rectangle_Breadth")
int breadth;
// getters and setters
public Rectangle()
{
}
public Rectangle(String shapeName,int length,int breadth)
{
super(shapeName);
this.length=length;
this.breadth=breadth;
}
// getters and setters
}
package org.arpit.javapostsforlearning;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
@Entity
@Table(name="CIRCLE")
public class Circle extends Shape{
@Column(name="Circle_Radius")
int radius;
public Circle()
{
}
public Circle(String shapeName,int radius)
{
super(shapeName);
this.radius=radius;
}
// getters and setters
}
package org.arpit.javapostsforlearning;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public class HibernateMain {
public static void main(String[] args) {
Shape shape=new Shape("Sqaure");
Rectangle rectangle=new Rectangle("Rectangle", 10, 20);
Circle circle=new Circle("Circle", 4);
Configuration configuration=new Configuration();
configuration.configure();
ServiceRegistry sr= new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
SessionFactory sf=configuration.buildSessionFactory(sr);
Session ss=sf.openSession();
ss.beginTransaction();
ss.save(shape);
ss.save(rectangle);
ss.save(circle);
ss.getTransaction().commit();
ss.close();
}
}
原文:http://javapostsforlearning.blogspot.in/2013/02/hibernate-inheritancetable-per-concrete.html
源代码:http://pan.baidu.com/share/link?shareid=3213551302&uk=3878681452
洋县白云宾馆
另见生成一张表:http://188029.net/hibernate/hib.html