how2j.cn

步骤 1 : 先运行,看到效果,再学习   
步骤 2 : 模仿和排错   
步骤 3 : 多对一注解   
步骤 4 : 一对多注解   
步骤 5 : 多对多注解   

步骤 1 :

先运行,看到效果,再学习

老规矩,先下载右上角的可运行项目,配置运行起来,确认可用之后,再学习做了哪些步骤以达到这样的效果。
步骤 2 :

模仿和排错

在确保可运行项目能够正确无误地运行之后,再严格照着教程的步骤,对代码模仿一遍。
模仿过程难免代码有出入,导致无法得到期望的运行结果,此时此刻通过比较正确答案 ( 可运行项目 ) 和自己的代码,来定位问题所在。
采用这种方式,学习有效果,排错有效率,可以较为明显地提升学习速度,跨过学习路上的各个槛。

推荐使用diffmerge软件,进行文件夹比较。把你自己做的项目文件夹,和我的可运行项目文件夹进行比较。
这个软件很牛逼的,可以知道文件夹里哪两个文件不对,并且很明显地标记出来
这里提供了绿色安装和使用教程:diffmerge 下载和使用教程
步骤 3 :

多对一注解

多对一改成用注解来实现
1. 把Category的id和name字段改为支持注解
注: 分类的getName上并没有加上@Column(name="name"),也可以达到映射的效果。 因为getName方法默认会被认为是字段映射。 除非加上了@Transient 才表示不进行映射
2. 把Product的getCategory进行多对一映射

@ManyToOne
@JoinColumn(name="cid")
public Category getCategory() {
return category;
}

@ManyToOne 表示多对一关系
@JoinColumn(name="cid") 表示关系字段是cid
对比xml中的映射方式:

<many-to-one name="category" class="Category" column="cid" />

3. 为hibernate.cfg.xml 添加Category的映射

<mapping class="com.how2java.pojo.Category" />

4. 运行TestHibernate
package com.how2java.pojo; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "category_") public class Category { int id; String name; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
package com.how2java.pojo; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; @Entity @Table(name = "product_") public class Product { int id; String name; float price; Category category; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") public int getId() { return id; } public void setId(int id) { this.id = id; } @Column(name = "name") public String getName() { return name; } public void setName(String name) { this.name = name; } @Column(name = "price") public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } @ManyToOne @JoinColumn(name="cid") public Category getCategory() { return category; } public void setCategory(Category category) { this.category = category; } }
<?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//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.characterEncoding">utf-8</property> <property name="connection.username">root</property> <property name="connection.password">admin</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/how2java/pojo/Product.hbm.xml" /> --> <mapping class="com.how2java.pojo.Product" /> <mapping class="com.how2java.pojo.Category" /> </session-factory> </hibernate-configuration>
步骤 4 :

一对多注解

在上一步的基础上做如下改动
1. 为Category再加product集合,并提供getter和setter

Set<Product> products;
public Set<Product> getProducts() {
return products;
}
public void setProducts(Set<Product> products) {
this.products = products;
}

2. 给getProducts方法加上一对多注解

@OneToMany(fetch=FetchType.EAGER)
@JoinColumn(name="cid")
public Set<Product> getProducts() {
return products;
}

@OneToMany 表示一对多,fetch=FetchType.EAGER 表示不进行延迟加载(FetchType.LAZY表示要进行延迟加载)
@JoinColumn(name="cid") 表示映射字段
对比xml中的映射方式:

<set name="products" lazy="false">
<key column="cid" not-null="false" />
<one-to-many class="Product" />
</set>

3. 修改TestHibernate为

SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session s = sf.openSession();
s.beginTransaction();
Category c = (Category) s.get(Category.class, 1);
s.getTransaction().commit();
s.close();
sf.close();
Set<Product> ps = c.getProducts();
for (Product p : ps) {
System.out.println(p.getName());
}
package com.how2java.pojo; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import javax.persistence.Table; @Entity @Table(name = "category_") public class Category { int id; String name; Set<Product> products; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @OneToMany(fetch=FetchType.EAGER) @JoinColumn(name="cid") public Set<Product> getProducts() { return products; } public void setProducts(Set<Product> products) { this.products = products; } }
package com.how2java.test; import java.util.Set; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import com.how2java.pojo.Category; import com.how2java.pojo.Product; public class TestHibernate { public static void main(String[] args) { SessionFactory sf = new Configuration().configure().buildSessionFactory(); Session s = sf.openSession(); s.beginTransaction(); Category c = (Category) s.get(Category.class, 1); s.getTransaction().commit(); s.close(); sf.close(); Set<Product> ps = c.getProducts(); for (Product p : ps) { System.out.println(p.getName()); } } }
步骤 5 :

多对多注解

1. 在基于XML配置的多对多知识点的基础上进行多对多注解的修改

2.像上两步那样,为Product,User,Category 加上类和属性注解

3. 加上多对一注解ManyToOne

4. 加上一对多注解OneToMany

5. ManyToMany
为Product的getUsers加上

@ManyToMany(cascade=CascadeType.ALL,fetch=FetchType.EAGER)
@JoinTable(
name="user_product",
joinColumns=@JoinColumn(name="pid"),
inverseJoinColumns=@JoinColumn(name="uid")
)
public Set<User> getUsers() {
return users;
}

对比Product.hbm.xml中的配置:

<set name="users" table="user_product" lazy="false">
<key column="pid" />
<many-to-many column="uid" class="User" />
</set>

为User的getProducts加上

@ManyToMany(cascade=CascadeType.ALL,fetch=FetchType.EAGER)
@JoinTable(
name="user_product",
joinColumns=@JoinColumn(name="uid"),
inverseJoinColumns=@JoinColumn(name="pid")
)
public Set<Product> getProducts() {
return products;
}

对比User.hbm.xml中的配置

<set name="products" table="user_product" lazy="false">
<key column="uid" />
<many-to-many column="pid" class="Product" />
</set>



6. hibernate.cfg.xml

<mapping class="com.how2java.pojo.Product" />
<mapping class="com.how2java.pojo.Category" />
<mapping class="com.how2java.pojo.User" />

7. 运行TestHibernate
package com.how2java.pojo; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.Table; @Entity @Table(name="user_") public class User { int id; String name; Set<Product> products; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @ManyToMany(cascade=CascadeType.ALL,fetch=FetchType.EAGER) @JoinTable( name="user_product", joinColumns=@JoinColumn(name="uid"), inverseJoinColumns=@JoinColumn(name="pid") ) public Set<Product> getProducts() { return products; } public void setProducts(Set<Product> products) { this.products = products; } }
package com.how2java.pojo; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.Table; @Entity @Table(name="product_") public class Product { int id; String name; float price; Category category; Set<User> users; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) public int getId() { return id; } public void setId(int id) { this.id = id; } @ManyToMany(cascade=CascadeType.ALL,fetch=FetchType.EAGER) @JoinTable( name="user_product", joinColumns=@JoinColumn(name="pid"), inverseJoinColumns=@JoinColumn(name="uid") ) public Set<User> getUsers() { return users; } public void setUsers(Set<User> users) { this.users = users; } @ManyToOne @JoinColumn(name="cid") public Category getCategory() { return category; } public void setCategory(Category category) { this.category = category; } public String getName() { return name; } public void setName(String name) { this.name = name; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } }
package com.how2java.pojo; import java.util.Set; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import javax.persistence.Table; @Entity @Table(name="category_") public class Category { int id; String name; Set<Product> products; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @OneToMany(fetch=FetchType.EAGER) @JoinColumn(name="cid") public Set<Product> getProducts() { return products; } public void setProducts(Set<Product> products) { this.products = products; } }
package com.how2java.test; import java.util.HashSet; import java.util.Set; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import com.how2java.pojo.Product; import com.how2java.pojo.User; public class TestHibernate { public static void main(String[] args) { SessionFactory sf = new Configuration().configure().buildSessionFactory(); Session s = sf.openSession(); s.beginTransaction(); // //增加3个用户 Set<User> users = new HashSet(); for (int i = 0; i < 3; i++) { User u =new User(); u.setName("user"+i); users.add(u); s.save(u); } //产品1被用户1,2,3购买 Product p1 = (Product) s.get(Product.class, 1); p1.setUsers(users); s.getTransaction().commit(); s.close(); sf.close(); } }
<?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//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.characterEncoding">utf-8</property> <property name="connection.username">root</property> <property name="connection.password">admin</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 class="com.how2java.pojo.Product" /> <mapping class="com.how2java.pojo.Category" /> <mapping class="com.how2java.pojo.User" /> </session-factory> </hibernate-configuration>


HOW2J公众号,关注后实时获知布最新的教程和优惠活动,谢谢。


问答区域    
2017-09-21 一对多和多对一
水不逝兮
产品类中: @ManyToOne @JoinColumn(name="cid") public Category getCategory() { return category; } 分类类中: @OneToMany(fetch=FetchType.EAGER) @JoinColumn(name="cid") public Set<Product> getProducts() { return products; } 这个cid字段是存在哪个表中?




1 个答案

人来人往 答案时间:2017-09-25
在多的那一方中




答案 或者 代码至少填写一项, 如果是自己有问题,请重新提问,否则站长有可能看不到




2017-09-01 关于一对多测试TestHibernate
dirs



将一对多、多对多关系修改为注解方式,为什么需要修改TestHibernate.java文件呢?

							

							


1 个答案

how2j 答案时间:2017-09-04
修改配置方式,不需要修改测试类吧,为什么会这么问呢?




答案 或者 代码至少填写一项, 如果是自己有问题,请重新提问,否则站长有可能看不到





2017-08-30 一对多注解修改测试类
2017-08-29 关于一对多测试
2017-03-15 错字
2017-02-28 我快该去实习了,如果这个网站的东西我掌握了90%,我实习工资能达到多少?




提问之前请登陆
关于 JAVA 框架-Hibernate-关系 的提问

尽量提供截图代码异常信息,有助于分析和解决问题。 也可进本站QQ群交流: 620943819
提问尽量提供完整的代码,环境描述,越是有利于问题的重现,您的问题越能更快得到解答。
对教程中代码有疑问,请提供是哪个步骤,哪一行有疑问,这样便于快速定位问题,提高问题得到解答的速度
在已经存在的几千个提问里,有相当大的比例,是因为使用了和站长不同版本的开发环境导致的,比如 jdk, eclpise, idea, mysql,tomcat 等等软件的版本不一致。
请使用和站长一样的版本,可以节约自己大量的学习时间。 站长把教学中用的软件版本整理了,都统一放在了这里, 方便大家下载: http://how2j.cn/k/helloworld/helloworld-version/1718.html

上传截图