Hibernate单表操作(四)——组件属性

来源:互联网 发布:牛知天骄潮汕鲜牛肉 编辑:程序博客网 时间:2024/06/13 23:42

转载请注明http://blog.csdn.net/uniquewonderq

1.什么是组件属性呢?

 它是指:实体类中的某个属性属于用户自定义的类的对象。

理解起来还是不容易:所以写点代码来说明问题:

  首先添加一个地址类:

package Entity;//地址类public class Address {private String postcode;//邮编private String phone;//电话private String address;//地址public Address(){}public Address(String postcode, String phone, String address) {this.postcode = postcode;this.phone = phone;this.address = address;}public String getPostcode() {return postcode;}public void setPostcode(String postcode) {this.postcode = postcode;}public String getPhone() {return phone;}public void setPhone(String phone) {this.phone = phone;}public String getAddress() {return address;}public void setAddress(String address) {this.address = address;}}

其次再在  student.hbm.xml的映射文件中加入:

        <component name="address" class="Address">        <propertyname="postcode"  column="POSTCODE"/>        <propertyname="phone"  column="PHONE"/>        <propertyname="address"  column="ADDRESS"/>        </component>

改变先前students类的构造方法:

public Students(int sid, String sname, String gender, Date birthday,Address address) {this.sid = sid;this.sname = sname;this.gender = gender;this.birthday = birthday;this.address=address;}

写测试方法:

public void testSaveStudents(){//保存学生用例对象//生成地址对象Address address=new Address("710024","15319728***","西安市");//生成学生对象Students s1=new Students(1,"张奇","男",new Date(),address);session.save(s1);//保存对象进入数据库,无须写sql语句}

因为表单结构发生变化,所以还要将hibernate.cfg.xml中的

 <property name="hbm2ddl.auto">update</property>  给为

 <property name="hbm2ddl.auto">create</property>

测试结果就是在新建了一个表,相比原来的表结构,新增了3列。(那三列是Address类的对象,该类有三个属性,自然增了3列)。


如下所示:

















0 0
原创粉丝点击