标签:ber configure any get config getname 单元测试 log test
首先定义2个实体类:Cate.java和Sub.java
单向一对多:一方有集合属性,包含多个多方,而多方没有一方的引用
1 package com.yztc.app.entity; 2 3 import javax.persistence.*; 4 import java.util.Set; 5 6 @Entity 7 @Table(name = "TB_CATE") 8 public class Cate { 9 @Id 10 @GeneratedValue//用于定义主键生成策略 11 @Column(name = "CID",length = 10) 12 private Long cid; 13 @Column(name = "NAME",length = 64) 14 private String name; 15 @OneToMany(cascade = CascadeType.ALL) 16 @JoinColumn(name = "CID") 17 private Set<Sub> subs; 18 19 public Set<Sub> getSubs() { 20 return subs; 21 } 22 23 public void setSubs(Set<Sub> subs) { 24 this.subs = subs; 25 } 26 27 public Long getCid() { 28 return cid; 29 } 30 31 public void setCid(Long cid) { 32 this.cid = cid; 33 } 34 35 public String getName() { 36 return name; 37 } 38 39 public void setName(String name) { 40 this.name = name; 41 } 42 43 public Cate() { 44 } 45 46 public Cate(String name) { 47 this.name = name; 48 } 49 }
1 package com.yztc.app.entity; 2 3 import javax.persistence.*; 4 5 @Entity 6 @Table(name = "TB_SUB") 7 public class Sub { 8 @Id 9 @GeneratedValue//用于定义主键生成策略 10 @Column(name = "SID",length = 10) 11 private Long sid; 12 @Column(name = "NAME",length = 64) 13 private String name; 14 15 16 public Sub() { 17 } 18 19 public Long getSid() { 20 21 return sid; 22 } 23 24 public void setSid(Long sid) { 25 this.sid = sid; 26 } 27 28 public String getName() { 29 return name; 30 } 31 32 public void setName(String name) { 33 this.name = name; 34 } 35 36 public Sub(String name) { 37 this.name = name; 38 } 39 }
二.单元测试:
1 package com.yztc.test; 2 3 4 import com.yztc.app.entity.Cate; 5 import com.yztc.app.entity.Sub; 6 import org.hibernate.Session; 7 import org.hibernate.SessionFactory; 8 import org.hibernate.Transaction; 9 import org.hibernate.cfg.Configuration; 10 import org.junit.After; 11 import org.junit.Before; 12 import org.junit.Test; 13 14 import java.util.HashSet; 15 import java.util.Set; 16 17 public class TestOneToMany { 18 19 private SessionFactory sf; 20 private Session session; 21 22 @Before 23 public void init(){ 24 sf = new Configuration().configure().buildSessionFactory(); 25 session = sf.openSession(); 26 27 } 28 //测试一对多单向 29 @Test 30 public void testSave(){ 31 Transaction transaction = session.beginTransaction(); 32 Cate cate = new Cate("手机"); 33 Set<Sub> sets = new HashSet<>(); 34 for (int i = 0; i < 10; i++) { 35 Sub sub = new Sub("魅族" + i); 36 sets.add(sub); 37 session.save(sub); 38 } 39 cate.setSubs(sets); 40 session.save(cate); 41 transaction.commit(); 42 43 44 } 45 @After 46 public void destory(){ 47 session.close(); 48 } 49 }
标签:ber configure any get config getname 单元测试 log test
原文地址:http://www.cnblogs.com/1218-mzc/p/7663396.html