组件是针对同一张表中的字段进行映射,作用是将字段多的一张表分成多个实体类来表示。
如:name与user
user表中有first_name及last_name。在实体类中,自定义一个Name类来表示first_name与last_name;
Name实体类:
package cn.framelife.mvc.entity; public class Name { private String firstName; private String lastName; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } }
User实体类:
package cn.framelife.mvc.entity; import java.io.Serializable; public class User implements Serializable { private Integer id; private Name name; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Name getName() { return name; } public void setName(Name name) { this.name = name; } }
User.hbm.xml:
<hibernate-mapping> <class name="cn.framelife.hibernate.entity.User" table="user" catalog="hibernate"> <id name="id" type="java.lang.Integer"> <column name="id" /> <generator class="native" /> </id> <component name="name" class="cn.framelife.hibernate.entity.Name"> <property name="firstName" column="first_name"></property> <property name="lastName" column="last_name"></property> </component> </class> </hibernate-mapping>
增加操作:
tx = session.beginTransaction(); Name name = new Name(); name.setFirstName("111"); name.setLastName("2222"); User user = new User(); user.setName(name); session.save(user); tx.commit();