摘自圣思园Hibenrate 26. 组件映射深度
解析 -37分钟
文件: Student.java, Contact.java, Student.hbm.xml
Student.java
class="java" name="code">public class Student
{
private String id;
private String name;
private Set contacts=new HashSet();
}
public class Contact
{
private String method;
private String address;
}
Student.hbm.xml
<hibernate-mapping package="component">
<class name="Student" table="test_student">
<id name="id" column="id" type="string">
<generator class="uuid"></generator>
</id>
<property name="name" column="name" type="string"/>
<set name="contacts" table="contact">
<key column="student_id"></key>
<!-- 这里配置了关联表Contact的元素 -->
<composite-element class="Contact">
<property name="method" type="string"/>
<property name="address" type="string"/>
</composite-element>
</set>
</class>
</hibernate-mapping>
生成SQL:
Hibernate: create table contact (student_id varchar2(255 char) not null, method varchar2(255 char), address varchar2(255 char))
Hibernate: create table test_student (id varchar2(255 char) not null, name varchar2(255 char), primary key (id))
Hibernate: alter table contact add constraint FK_r3jhjlmx2uie72qpg7l3sedib foreign key (student_id) references test_student
插入
Session session=HibernateUtil.openSession();
Contact c1=new Contact("phone","233333","1");
Contact c2=new Contact("qq","233333","1");
Student s=new Student("1", "li",ArraysHelper.asSet(c1,c2) );
session.save(s);
Transaction tx=session.beginTransaction();
tx.commit();
结果:
- 大小: 55.7 KB
- hibernate_a2.rar (25.8 KB)
- 下载次数: 0