博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
hibernate注解方式
阅读量:6767 次
发布时间:2019-06-26

本文共 24341 字,大约阅读时间需要 81 分钟。

hot3.png

(A) 配置hibernate日志

 1、 为防止冲突,先将slf4j-nop的jar包(它也是slf的一个实例)去除

 2、 加入log4j的jar包 commons-logging-1.1.1.jar,log4j-1.2.14.jar。

 3、 加入转换包 slf4j-log4j12-1.5.10.jar

 4、 src下添加log4j.properties 配置文件

 5、 在hibernate4开始,已经继承了注解的方式,如果是hibernate3以前的版本,就需要加入annotation的jar

### direct log messages to stdout ###log4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.Target=System.outlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c:%L - %m%n### direct messages to file hibernate.log ####log4j.appender.file=org.apache.log4j.FileAppender#log4j.appender.file.File=hibernate.log#log4j.appender.file.layout=org.apache.log4j.PatternLayout#log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n### set log levels - for more verbose logging change 'info' to 'debug' ###log4j.rootLogger=warn, stdout#log4j.logger.org.hibernate=info#log4j.logger.org.hibernate=debug### log HQL query parser activity#log4j.logger.org.hibernate.hql.ast.AST=debug### log just the SQL#log4j.logger.org.hibernate.SQL=debug### log JDBC bind parameters ####log4j.logger.org.hibernate.type=info#log4j.logger.org.hibernate.type=debug### log schema export/update ###log4j.logger.org.hibernate.tool.hbm2ddl=debugg### enable the following line if you want to track down connection ###### leakages when using DriverManagerConnectionProvider ####log4j.logger.net.sf.hibernate.connection.DriverManagerConnectionProvider=trace

(B) hibernate 配置表结构

 1.一对一(包括联合主建的生成)

package com.one.to.one.bean;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.persistence.JoinColumn;import javax.persistence.JoinColumns;import javax.persistence.OneToOne;@Entitypublic class Person {	private int id;	private String name;	private IdCard idCard;	@Id	@GeneratedValue	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;	}/** *    1.@JoinColumn 写入引入外键字段在数据库中的名称,一般来说会默认给,所以写入的时候一定要注意; *    3.只要是涉及了外键的引入,就要配置JoinColumn; *    2.referencedColumnName 引用的另外一张表的列名,防止不是主建关联的情况,还有就是联合主建; */	@OneToOne	@JoinColumns( { 		@JoinColumn(name = "num_id", referencedColumnName = "num"),			@JoinColumn(name="age_id",referencedColumnName="age") })	public IdCard getIdCard() {		return idCard;	}	public void setIdCard(IdCard idCard) {		this.idCard = idCard;	}}
package com.one.to.one.bean;import javax.persistence.Entity;import javax.persistence.Id;import javax.persistence.IdClass;import javax.persistence.OneToOne;@Entity@IdClass(IdCardPk.class)public class IdCard {private int num;private int age;private Person person;@Idpublic int getNum() {return num;}public void setNum(int num) {this.num = num;}@Idpublic int getAge() {return age;}public void setAge(int age) {this.age = age;}/** * 在双向关联中肯定有一处是写入了mappedBy,一般是在没有引用外键即被引用的对象中写入; */@OneToOne(mappedBy="idCard")public Person getPerson() {return person;}public void setPerson(Person person) {this.person = person;}}
package com.one.to.one.bean;import java.io.Serializable;public class IdCardPk implements Serializable{private int num;private int age;public int getNum() {return num;}public void setNum(int num) {this.num = num;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}}
package com.one.to.one.bean;import javax.persistence.CascadeType;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.FetchType;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.persistence.OneToOne;@Entitypublic class Husband {private int id;private String name;private int age;private Wife wife;@Id@GeneratedValuepublic int getId() {return id;}public void setId(int id) {this.id = id;}@Column(name = "husband_Name")public String getName() {return name;}public void setName(String name) {this.name = name;}@OneToOne(mappedBy = "husband", cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)public Wife getWife() {return wife;}public void setWife(Wife wife) {this.wife = wife;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}}
package com.one.to.one.bean;import javax.persistence.CascadeType;import javax.persistence.Entity;import javax.persistence.FetchType;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.persistence.JoinColumn;import javax.persistence.OneToOne;import javax.persistence.Transient;@Entitypublic class Wife {private int id;private int num;private String name;private Husband husband;@Id@GeneratedValuepublic int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {his.name = name;}@OneToOne(cascade={CascadeType.ALL},fetch=FetchType.EAGER)@JoinColumn(name="husband_Id",referencedColumnName="id")public Husband getHusband() {return husband;}public void setHusband(Husband husband) {this.husband = husband;}@Transientpublic int getNum() {return num;}public void setNum(int num) {this.num = num;}}

 2.多对一

package com.many.to.one.bean;import java.util.Set;import javax.persistence.CascadeType;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.FetchType;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.persistence.OneToMany;import org.hibernate.annotations.BatchSize;import org.hibernate.annotations.Cache;import org.hibernate.annotations.CacheConcurrencyStrategy;@Entity@BatchSize(size = 5)@Cache(usage=CacheConcurrencyStrategy.READ_WRITE)public class Ogroup {private int id;private String name;private Set
owners;@Id@GeneratedValue@Column(updatable=true)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(cascade={CascadeType.ALL},mappedBy="ogroup",fetch=FetchType.LAZY)public Set
getOwners() { return owners;}public void setOwners(Set
owners) { this.owners = owners;}}
package com.many.to.one.bean;import javax.persistence.CascadeType;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.FetchType;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.persistence.JoinColumn;import javax.persistence.ManyToOne;import org.hibernate.annotations.BatchSize;import org.hibernate.annotations.Cache;import org.hibernate.annotations.CacheConcurrencyStrategy;/** * @Cache   缓存的配置针对于的是load itertor get 等这些方法 *          对于query.list()方法,要独立的想它 ,它跟别的是不一样的; */@Entity@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)public class Owner {private int id;private String name;private String despotion;private Ogroup ogroup;@Id@GeneratedValuepublic 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;}@Column(updatable=false)public String getDespotion() {    return despotion;}public void setDespotion(String despotion) {    this.despotion = despotion;}/** * 1.fetch=FetchType.EAGER 立即取得关联对象的数据库值; * 2.如果是默认值,要取关联对象的信息,调用getGroup()的时候,会重新发送一条数据库语句,前提是session没有关闭; * 3.如果session关闭,想要获取到关联对象的值,就要写fetch配置; */@ManyToOne(cascade={CascadeType.ALL},fetch=FetchType.EAGER)@JoinColumn(name="group_id")public Ogroup getOgroup() {    return ogroup;}public void setOgroup(Ogroup ogroup) {    this.ogroup = ogroup;}}
package com.many.to.one.bean;import javax.persistence.CascadeType;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.persistence.JoinColumn;import javax.persistence.ManyToOne;@Entitypublic class Car {private int id;private String name;private Type type;@Id@GeneratedValuepublic 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;}@ManyToOne(cascade={CascadeType.ALL})@JoinColumn(name="car_type_Id",referencedColumnName="id")public Type getType() {    return type;}public void setType(Type type) {    this.type = type;}}
package com.many.to.one.bean;import java.util.Set;import javax.persistence.CascadeType;import javax.persistence.Entity;import javax.persistence.FetchType;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.persistence.OneToMany;@Entitypublic class Type {private int id;private String name;private Set
cars;@Id@GeneratedValuepublic 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(mappedBy="type",cascade={CascadeType.ALL},fetch=FetchType.EAGER)public Set
getCars() {    return cars;}public void setCars(Set
cars) {    this.cars = cars;}}

 3.多对多

package com.many.to.many.bean;import java.util.Set;import javax.persistence.CascadeType;import javax.persistence.Entity;import javax.persistence.FetchType;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.persistence.JoinColumn;import javax.persistence.JoinTable;import javax.persistence.ManyToMany;@Entitypublic class Man {	private int id;	private String name;private Set
womens; @Id @GeneratedValue 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; } /** * 1.如果两者之间有关联的时候,对于A B 两个 如果默认,那么就是两者都要保存一次,设置了cascade.ALL所有的dml都会设置了级连接; * 2.CascadeType.ALL 任何dml;CascadeType.PERSIST 任何保存;CascadeType.REMOVE 任何删除时候,执行关联; * 3.cascade在Man中设置了,只对Man有用,当保存womens的时候,相关联的Man不会存入; * 4.@JoinTable 配置中间表的信息,name是中间表的名称,前后分别是两个字段的名称 * 5.women类中必须要写(mappedBy="womens"),如果这个注解要分开写,不能写在配置中间表的类中. */@ManyToMany(cascade={CascadeType.ALL},fetch=FetchType.EAGER)@JoinTable(name="center_table",joinColumns={ @JoinColumn(name="man_id",referencedColumnName="id") },inverseJoinColumns={@JoinColumn(name="women_id",referencedColumnName="id")}) public Set
getWomens() { return womens; } public void setWomens(Set
womens) { this.womens = womens; }}
package com.many.to.many.bean;import java.util.Set;import javax.persistence.CascadeType;import javax.persistence.Entity;import javax.persistence.FetchType;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.persistence.ManyToMany;@Entitypublic class Women {private int id;private String name;private Set
mans;@Id@GeneratedValuepublic 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(mappedBy="womens"    ,cascade={CascadeType.ALL},fetch=FetchType.EAGER)public Set
getMans() {    return mans;}public void setMans(Set
mans) {    this.mans = mans;}}

(C) hiberneate.cfg.xml 配置二级缓存

 1.如果用ehcache这个缓存类,在src下加入ehcache.xml文件

 2.缓存的具体详解在各个class中

org.hibernate.dialect.Oracle9Dialect
jdbc:oracle:thin:@127.0.0.1:1521:orcl
new
sa
oracle.jdbc.OracleDriver
orcl
true
true
update
org.hibernate.cache.EhCacheProvider
true
true
thread

(D) DAO

 1.CacheDao

package dao;import org.hibernate.Query;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cache.EhCacheProvider;import org.hibernate.cache.HashtableCacheProvider;import org.hibernate.cfg.AnnotationConfiguration;import com.many.to.one.bean.Ogroup;import com.many.to.one.bean.Owner;/** * session缓存为一级缓存,不同的session会重新发送hql语句; * SessionFactory 二级缓存,跨越session存在; * load get itroter 等方法默认二级缓存;但是也要配置; * query查询方法专门开启查询缓存,同一个q.list()两次,并q.setCachale(true)不会重发sql; */public class CacheDao {	public void getUserTest1(Session session,Session session2){		 session.createQuery("from Ogroup").list();		 session2.createQuery("from Ogroup").list();				 session.clear();		 session.close();	}	public void getUserTest2(Session session,Session session2){		Ogroup group = (Ogroup) session.load(Ogroup.class, 2);		Ogroup group2 = (Ogroup) session2.load(Ogroup.class, 2);				System.out.println(group.getName());		//System.out.println(group.getOwners().size());		System.out.println(group2.getName());		//System.out.println(group2.getOwners().size());	}	public void getUserTest3(SessionFactory sf) {		Session session = sf.openSession();		Session session2 = sf.openSession();		session.get(Ogroup.class, 2);		try {			Thread.sleep(2000);		} catch (InterruptedException e) {			// TODO Auto-generated catch block			e.printStackTrace();		}		session2.get(Ogroup.class, 2);	sf.close();	}	public void getUserTest4(SessionFactory sf){		Session session = sf.openSession();		Session session2 = sf.openSession();		Query q = session.createQuery("from Ogroup");		Query q2 = session2.createQuery("from Ogroup");//		q.setCacheable(true);		q.list();		q2.list();			    sf.close();	}	public void getUserTest5(SessionFactory sf){		Session session = sf.openSession();		Query q = session.createQuery("from Owner");		q.setCacheable(true);		q.list();		q.list();	    sf.close();	}	public static void main(String[] args) {		AnnotationConfiguration cfg = new AnnotationConfiguration().configure();		SessionFactory sf = cfg.buildSessionFactory();		Session session = sf.openSession();		Session session2 = sf.openSession();//		new CacheDao().getUserTest2(session,session2);		new CacheDao().getUserTest5(sf);//		new CacheDao().getUserTest1(session,session2);	}}

 2.Car_Type_Dao

package dao;import java.math.BigDecimal;import java.util.HashSet;import java.util.List;import java.util.Set;import javax.persistence.FetchType;import javax.persistence.Query;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.AnnotationConfiguration;import com.many.to.one.bean.Car;import com.many.to.one.bean.Type;import com.one.to.one.bean.Husband;import com.one.to.one.bean.Wife;public class Car_Type_Dao {	public void save(Session session) {		Car car = new Car();		car.setName("car01");		Car car2 = new Car();		car2.setName("car02");		Type type = new Type();		type.setName("奔驰007");		car.setType(type);		car2.setType(type);		session.beginTransaction();		session.save(car);			session.save(car2);	//		session.save(type);		session.getTransaction().commit();	}	public void getCar(Session session) {		Type type = (Type)session.load(Type.class, 2);		System.out.println(type.getName());		session.close();		System.out.println(type.getCars().size());	}	public void deleteCar(Session session){		Car car = (Car)session.load(Car.class, 4);		session.beginTransaction();		session.delete(car);		session.getTransaction().commit();	}	/**	 * 1.session.load 数据库检查级联关系,当删除car的id是1时,关联的type就会被删掉,	 * 反过来type所关联的car又会被全部删掉;	 * 2.session.load 数据库检查级联关系,当删除type的时候,car也删掉了;	 * 2.不使用session.load的时候,就不会有级联的关系了,直接设置了id是1,但是删除type的时候就会报错,	 *    原因是没有检查级联关系,就会产生异常,有外键的引用关系;	 * 3.解决的办法是,将其中的user.setType(null)断开级联关系;	 * 4.也可用hql语句来解决,hql语句是不检查级联关系的;	 * 5.铁律:hql跟sql一样,绝不涉及级联关系,而只要使用session的方法除delete特殊外,就会涉及级联关系;	 */	public void deleteType(Session session){		Type type = (Type)session.load(Type.class, 4);		session.beginTransaction();		session.delete(type);		session.getTransaction().commit();	}	/**	 * 1.hql语句的查询,跟级联是没有关系的,只跟fetch=FetchType.EAGER有关系;	 */	public void getAllCar(Session session){		org.hibernate.Query q = session.createQuery("from Type");		List
al =q.list(); session.clear(); session.close(); for (int i = 0; i < al.size(); i++) { Type type = al.get(i); System.out.println(type.getCars().size()); } } public static void main(String[] args) { AnnotationConfiguration cfg = new AnnotationConfiguration() .configure("hibernate.cfg.xml"); SessionFactory sf = cfg.buildSessionFactory(); Session session = sf.openSession();// new Car_Type_Dao().save(session);// new Car_Type_Dao().getCar(session);// new Car_Type_Dao().deleteCar(session); new Car_Type_Dao().getAllCar(session); //session.close(); sf.close(); }}

 3.GroupDao

package dao;import java.util.HashSet;import java.util.List;import java.util.Set;import javax.persistence.CascadeType;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.AnnotationConfiguration;import com.many.to.one.bean.Ogroup;import com.many.to.one.bean.Owner;public class GroupDao {	/** 没有cascade={CascadeType.ALL},手动存如两个对象 */public void save(Session session){	Ogroup ogroup = new Ogroup();	ogroup.setName("湖北省水利厅");	Owner user = new Owner();	user.setName("jack");	user.setOgroup(ogroup);	session.beginTransaction();	session.save(user);	session.save(ogroup);	session.getTransaction().commit();}/** 1.加入了cascade={CascadeType.ALL} 后,只存去一个对象,另外的一个对象也存入 *  2.以存入user为主导 */public void save2(Session session){	Ogroup ogroup = new Ogroup();	ogroup.setName("湖北省水利厅");	Owner user = new Owner();	user.setName("Jack");	user.setOgroup(ogroup);		Owner user2 = new Owner();	user2.setName("Marry");	user2.setOgroup(ogroup);	session.beginTransaction();	session.save(user);	session.save(user2);	//session.save(ogroup);	session.getTransaction().commit();}/** * 1.以存入group为主导 */public void saveGroup(Session session){	Ogroup ogroup = new Ogroup();	ogroup.setName("地市州");	Owner user = new Owner();	user.setName("Jack2");	user.setOgroup(ogroup);	Owner user2 = new Owner();	user2.setName("Marry2");	user2.setOgroup(ogroup);	session.beginTransaction();	Set
st = new HashSet
(); st.add(user);st.add(user2); session.save(ogroup); session.getTransaction().commit();}public void updateGroup(Session session){ //Ogroup group = (Ogroup) session.load(Ogroup.class, 2); Ogroup group = new Ogroup(); session.beginTransaction(); group.setId(2); group.setName("长江委2"); session.update(group); session.getTransaction().commit(); session.close();}/** * 1.没有load,没有实现了级联关系的映射,如果更新字段,其余的字段会变为垃圾数据; * 2.load后,实现了级联关系,关联相关表信息会更新; */public void updateUser(Session session){ //Owner user = (Owner)session.load(Owner.class,1); Owner user = new Owner(); user.setId(1); user.setName("Jack2"); session.beginTransaction(); session.update(user); session.getTransaction().commit(); session.close();}public void getUserTest(Session session){ Ogroup group = (Ogroup) session.load(Ogroup.class, 2); Owner user = (Owner) session.get(Owner.class,3); System.out.println(group.getName()); System.out.println(group.getOwners().size()); System.out.println(user.getName()); System.out.println(user.getOgroup().getName()); session.clear(); session.close();}/** * 1+N:1.session.createCriteria没有这个问题,本身就有left join on; * 2.session.createQuery,查询user时候,由于它的fetchType默认是eager,那么在查询user的时候; * 将group都取出来了,本来是一条语句,变成了N条; * 解决办法:1.fetchType设为LAZY; * 2.@BatchSize()在对应的N条数据库表的类上加,(size=5),一次性去除5条; */public void getUserTest2(Session session){ List
a = session.createQuery("from Owner").list(); session.clear(); session.close();}public void getUserTest3(Session session){ session.createCriteria(Owner.class).list(); session.clear(); session.close();}public static void main(String[] args) { AnnotationConfiguration cfg = new AnnotationConfiguration().configure(); SessionFactory sf = cfg.buildSessionFactory(); Session session = sf.openSession(); new GroupDao().getUserTest3(session); }}

 4. Husband_Wife_Dao

package dao;import javax.persistence.CascadeType;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.AnnotationConfiguration;import com.one.to.one.bean.Husband;import com.one.to.one.bean.Wife;public class Husband_Wife_Dao {	public void saveOrUpdate(Session session){		Wife wife = new Wife();		wife.setName("Marry_saveUpdate");		session.beginTransaction();		session.saveOrUpdate(wife);		session.getTransaction().commit();			}public void save(Session session){	Wife wife = new Wife();	wife.setName("Marry");	Wife wife2 = new Wife();	wife2.setName("Marry2");	Husband husband = new Husband();	husband.setName("Jack");		/**	 * #如果用这两行:1.husband.setWife(husband);	 *              2.session.save(husband);	 *              # 外键的引用是存不进去的;	 * #要根据数据库表的存入顺序:1.wife.setHusband(husband);	 *                          2.session.save(wife);	 */	wife2.setHusband(husband);	wife.setHusband(husband);	session.beginTransaction();	session.save(wife);	session.save(wife2);	session.getTransaction().commit();	}public void getHusband(Session session){	Husband husband=(Husband)session.get(Husband.class, 2);	System.out.println(husband.getName());	System.out.println(husband.getWife().getName());}/** *  (1)update更新字段: 1.在xml配置中property 的update属性; *                     2.注解方式中@cumlun(update=true); *            以上两种解释为从不更新,不灵活,不方便; *                 3.xml配置中 在clsss标签中写dynamic—update='true',表示没有更改的记录就不会更新; *                 4.在自身的试验中,发现3.0的hibernate注解中默认就是第三种情况.不用自己去设置; *  (2)update级联更新: 1.CascadeType.ALL任何操作级联都更新; *                    2.CascadeType.merig的时候,使用session.merig方法才会更新级联; *                    3.更新和delete一样,如果不使用session.load实现级联查询,变不会更新级联; */public void updateHusband(Session session){	Husband husband=(Husband)session.get(Husband.class, 2);	husband.setAge(4);	husband.getWife().setName("Marry");	session.beginTransaction();	session.update(husband);	session.getTransaction().commit();	}public void deleteWife(Session session){	Wife wife = new Wife();	wife.setId(21);	session.beginTransaction();	session.delete(wife);	session.getTransaction().commit();}public static void main(String[] args) {	AnnotationConfiguration cfg = new AnnotationConfiguration().configure("hibernate.cfg.xml");	SessionFactory sf = cfg.buildSessionFactory();	Session session = sf.openSession();//	new Husband_Wife_Dao().save(session);//	new Husband_Wife_Dao().getHusband(session);//	new Husband_Wife_Dao().updateHusband(session);	new Husband_Wife_Dao().deleteWife(session);	session.close();	sf.close();}}

 5.ManDao

package dao;import java.util.HashSet;import java.util.Set;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.AnnotationConfiguration;import com.many.to.many.bean.Man;import com.many.to.many.bean.Women;public class ManDao {	/**	 * save2 方法在cascade默认不写的情况下,手动存入两个变量;	 * @param session	 */	public void save2(Session session) {		Women womens = new Women();		womens.setName("Marry");		Women womens2 = new Women();//		womens2.setId(2);		womens2.setName("Marry2");		Man man = new Man();		man.setName("Jack");		Set
st = new HashSet
(); st.add(womens); st.add(womens2); man.setWomens(st); Transaction tc = session.beginTransaction(); session.save(man); session.save(womens); session.save(womens2); session.getTransaction().commit(); session.close(); } public void save(Session session) { Women womens = new Women(); womens.setName("Marry"); Women womens2 = new Women(); womens2.setName("Marry2"); Man man = new Man(); man.setName("Jack"); Set
st = new HashSet
(); st.add(womens); st.add(womens2); man.setWomens(st); Transaction tc = session.beginTransaction();// session.save(womens);// session.save(womens2); session.save(man); session.getTransaction().commit(); } public void getWomens(Session session) { Women women = (Women)session.load(Women.class, 8); session.clear(); System.out.println(women.getName()); System.out.println(women.getMans().size()); } public static void main(String[] args) { AnnotationConfiguration cfg = new AnnotationConfiguration().configure(); SessionFactory sf = cfg.buildSessionFactory(); Session session = sf.openSession(); new ManDao().getWomens(session); }}

小技巧:通过hibernate来进行插入操作的时候,不管是一对多、一对一还是多对多,都只需要记住一点,在哪个实体类声明了外键,就由哪个类来维护关系,在保存数据时,总是先保存的是没有维护关联关系的那一方的数据,后保存维护了关联关系的那一方的数据,如:

Person p = new Person();p.setName("xiaoluo");session.save(p);            IDCard card = new IDCard();card.setNo("1111111111");card.setPerson(p);session.save(card);

转载于:https://my.oschina.net/gaoguofan/blog/753436

你可能感兴趣的文章