The main research in this article is the related content of Hibernate component mapping, as follows.
The attributes of the component association map are complex types of persistent classes, but not entity classes, that is, there is no table in the database corresponding to this attribute, but the attributes of this class must be persisted.
For example: The name of a foreigner is divided into firstName and lastName.
public class MyName {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;}}Note: This is a component class that does not map to the database, and it corresponds to the name field in People.
public class People {private Integer pid;/*The names are combined through the MyName class, that is, component association*/private MyName name;public Integer getPid() {return pid;}public void setPid(Integer pid) {this.pid = pid;}public MyName getName() {return name;}public void setName(MyName name) {this.name = name;}}Note: The name field is implemented through component (MyName class) association.
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.lixue.bean"> <class name="People" table="t_people"> <id name="pid"> <generator/generator//id> <!-- Mapping primary keys through Component--> <component name="name"> <property name="firstName" /> <property name="lastName" /> </component> </class> </hibernate-mapping>
Note: Component associations are mapped through the <component> tag.
public void testSave1(){/*Define Session and Things*/Session session = null;Transaction transaction = null;try {/*Get Session and enable Things*/session = HibernateUtils.getSession();transaction = session.beginTransaction();/*Create a name*/MyName myName = new MyName();myName.setFirstName("George");myName.setLastName("Washington");/*Create a person and set attributes*/People people = new People(); people.setName(myName);session.save(people);/*Submit things*/transaction.commit();}catch (Exception e) {e.printStackTrace();transaction.rollback();} finally{HibernateUtils.closeSession(session);}}The above is all the detailed explanation of the Hibernate component mapping code in this article, I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!