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

时间:2021-02-23 05:09:52

转载请注明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">
        	<property	name="postcode"  column="POSTCODE"/>
        	<property	name="phone"  column="PHONE"/>
        	<property	name="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列)。


如下所示:

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