1.多对一
product----category
category.hbm.xml <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.h.pojo"> <class name="Category" table="category_"> <id name="id" column="id"> <generator class="native"> </generator> </id> <property name="name" /> </class> </hibernate-mapping>
product.hbm.xml <?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.h.pojo"> <class name="Product" table="product_"> <id name="id" column="id"> <generator class="native"></generator> </id> <property name="name" /> <property name="price" />
<many-to-one name="category" class="Category" column="cid"></many-to-one> product多 对 一category
</class> </hibernate-mapping>
hibernate.cfg.xml <?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8</property> <property name="connection.username">root</property> <property name="connection.password">123456</property> <!-- SQL dialect --> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <property name="current_session_context_class">thread</property> <property name="show_sql">true</property> <property name="hbm2ddl.auto">update</property> <mapping resource="com/h/pojo/Product.hbm.xml" /> <mapping resource="com/h/pojo/Category.hbm.xml"/> </session-factory> </hibernate-configuration>
测试类:
public class Test1 { public static void main(String[] args) { SessionFactory factory=new Configuration().configure().buildSessionFactory(); Session session = factory.openSession(); session.beginTransaction(); Category c =new Category(); c.setName("c1"); session.save(c); Product p = (Product) session.get(Product.class, 2); p.setCategory(c); session.update(p); session.getTransaction().commit(); session.close(); factory.close(); } }
2.一对多
category 对 product,与多对一相反,就是一对多
测试类:
3.多对多
product ---- user
一种Product可以被多个User购买
一个User可以购买多种Product
所以Product和User之间的关系是多对多 many-to-many
要实现多对多关系,必须有一张中间表 user_product 用于维护 User和Product之间的关系
测试类:
数据库: