目前是有两个实体类Room 和 Customer , 分析: 在实体间:有如下关系 Room 里有多个Customer 一对多 Customer 属于那一个Room 多对一 在关系型数据库中:有如下关系 在customer 表中有一个room 的外键 实体类的编写: Room.java @Entity @Table(name="room") public class Room { @Id @GeneratedValue private int id; @Version private int version; @Column(name="room_name") private String roomName; @Temporal(TemporalType.TIMESTAMP) private Date comeTime; @Basic private double money; @OneToMany(mappedBy="room",targetEntity=Customer.class,fetch=FetchType.EAGER,cascade=(CascadeType.ALL)) //相当于hibernate中的inverse=true mappedBy 在那一端就说明那一端不负责维护关系 private Set<Customer> customers = new HashSet<Customer>(); /***瞬时不会映射到数据库*/ @Transient private int hours; getters(); setters(); } Customer.java @Entity @Table(name = "customer") public class Customer { @Id @GeneratedValue private int id; @Version private int version; @Column(name = "customer_name", unique = true) private String customerName; @Basic private int age; @ManyToOne @JoinColumn(name = "roomId") private Room room; getters(); settrers(); } hibernateExpSQL.java 工具类导出sql脚本 /** * 导出一个本地的sql 文件 * @param file */ public static void expSql(String file){ //读取配置文件 AnnotationConfiguration().configure("hibernate.cfg.xml"); //使用jpa 注解的方法 // Configuration cfg = new Configuration().configure("hibernate.cfg.xml"); AnnotationConfiguration cp = new AnnotationConfiguration().configure("hibernate.cfg.xml"); //创建SchemaExport对象 SchemaExport export = new SchemaExport(cp); export.setFormat(true); export.setDelimiter(";"); export.setOutputFile(file); //创建数据库表 export.create(true,false); } hibernate.cfg.xml <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://127.0.0.1/hibernate2</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">root</property> <property name="hibernate.connection.isolation">2</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.show_sql">true</property> <property name="hibernate.hbm2ddl.auto">update</property> <property name="hibernate.format_sql">true</property> <mapping class="com.wlzx.modle.Room"/> <mapping class="com.wlzx.modle.Customer"/> </session-factory> </hibernate-configuration>
结果如下: 映射数据库