时间:2021-07-01 10:21:17 帮助过:22人阅读
首先有一个文章类(Article)类中有id、title、content、postTime等属性。 package entity;import java.util.Date;public class Article {private Integer id;private String title;private String content;private Date postTime;public Integer getId() {r
首先有一个文章类(Article)类中有id、title、content、postTime等属性。
package entity; import java.util.Date; public class Article { private Integer id; private String title; private String content; private Date postTime; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Date getPostTime() { return postTime; } public void setPostTime(Date postTime) { this.postTime = postTime; } }
然后看他的子类,Topic类和Reply类。他们除了父类的属性外还有自己独特的属性。
package entity; public class Topic extends Article{ private int type; public int getType() { return type; } public void setType(int type) { this.type = type; } }
package entity; public class Reply extends Article{ private int floor; public int getFloor() { return floor; } public void setFloor(int floor) { this.floor = floor; } }
继承映射的方式有三种方式,我们一个个看:
方式一:将父类和子类的信息存放在同一个表中,然后在该数据表中有个字段用来表示该条记录的类型,其中子类独有的属性允许为空。我们看一下映射配置文件。
方式二:父类和子类不在同一张表中,且每一个类一张表,抽象类对应一张表,这是配置子类使用joined-subclass
方式三:每一个类单独一张表,并且抽象类不对应一张表,子类对应的数据库表中对应全部的属性,包括从父类继承的信息。
然后看一下测试类,三种方式测试类相同,只有方式三的save方法中因为抽象类没有单独的数据表因此不能存储他们父类的信息。
package test; import org.hibernate.Session; import org.hibernate.Transaction; import entity.Article; import entity.Reply; import entity.Topic; import factory.HibernateSessionFactory; public class Test { private Session session = null; private Transaction tran = null; @org.junit.Test public void save() { session = HibernateSessionFactory.getSession(); tran = session.beginTransaction(); try{ Article article = new Article(); article.setId(1); article.setTitle("这是一个Article"); Topic topic = new Topic(); topic.setId(2); topic.setTitle("这是一个Topic"); Reply reply = new Reply(); reply.setId(3); reply.setTitle("这是一个reply"); session.save(article); session.save(topic); session.save(reply); tran.commit(); }catch(Exception e){ tran.rollback(); } } @org.junit.Test public void Get() { session = HibernateSessionFactory.getSession(); tran = session.beginTransaction(); try{ Article a = (Article)session.get(Article.class, 1); Topic t = (Topic)session.get(Topic.class, 2); Reply r = (Reply)session.get(Reply.class, 3); System.out.println(a.getTitle()); System.out.println(t.getTitle()); System.out.println(r.getTitle()); tran.commit(); }catch(Exception e){ tran.rollback(); } } }