1. 程式人生 > >[Hibernate]七種關聯關係配置檔案和測試例項詳解

[Hibernate]七種關聯關係配置檔案和測試例項詳解

用了一天整理下來。所有關係分為以下七種:

單向【1-1】

雙向【1-1】

單向【1-N】

雙向【1-N】

單向【N-1】

單向【N-N】

雙向【N-N】

1單向【1-1】

基於外來鍵的單向【1-1】
是【N-1】的特殊形式,要求【N】方唯一。
基於外來鍵的單向1-1只需要在原有的<many-to-one>元素增加unique=true屬性,用以表示N的一端必須唯一

===》將單向【N-1】變為基於外來鍵的單向【1-1】關聯關係。

package OneToOneSingle;

public class User {
	private Integer Userid;
	private String username;
	private String password;
	private UserInfo userinfo;
	public Integer getUserid() {
		return Userid;
	}
	public void setUserid(Integer userid) {
		Userid = userid;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public UserInfo getUserinfo() {
		return userinfo;
	}
	public void setUserinfo(UserInfo userinfo) {
		this.userinfo = userinfo;
	}
	
}
package OneToOneSingle;

public class UserInfo {
	private Integer InfoId;
	private String address;
	private String mail;
	public Integer getInfoId() {
		return InfoId;
	}
	public void setInfoId(Integer infoId) {
		InfoId = infoId;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public String getMail() {
		return mail;
	}
	public void setMail(String mail) {
		this.mail = mail;
	}
	
	
	
}
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
	<class name="OneToOneSingle.User" table="User">
		<id name="Userid">
			<generator class="native"></generator>
		</id>
		<property name="username" />
		<property name="password"></property>

		<many-to-one name="userinfo" class="OneToOneSingle.UserInfo"
			column="info_id" unique="true" cascade="all" />
			<!-- cascade為操作user物件時,同時聯級儲存 userinfo物件-->


	</class>
</hibernate-mapping>

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
	<class name="OneToOneSingle.UserInfo" table="userInfo">
		<!-- 主鍵對應 -->
		<id name="InfoId">
			<generator class="native"></generator>
		</id>
		<property name="address" />
		<property name="mail"></property>

	</class>
</hibernate-mapping>

2雙向【1-1】

基於主鍵的雙向【1-1】
兩個關聯表使用相同的主鍵值,其中一個表的主鍵共享另外一個表的主鍵。
使用標籤<one-to-one>

constrained放錯位置會導致外來鍵死鎖。

package OneToOneDouble;

public class Husband {
	private Integer Id;
	private String husbanName;
	private Wife wife;
	public Integer getId() {
		return Id;
	}
	public void setId(Integer id) {
		Id = id;
	}
	public String getHusbanName() {
		return husbanName;
	}
	public void setHusbanName(String husbanName) {
		this.husbanName = husbanName;
	}
	public Wife getWife() {
		return wife;
	}
	public void setWife(Wife wife) {
		this.wife = wife;
	}
	

}
package OneToOneDouble;

public class Wife {

	private Integer Id;
	private String wifeName;
	private Husband husband;
	public Integer getId() {
		return Id;
	}
	public void setId(Integer id) {
		Id = id;
	}
	public String getWifeName() {
		return wifeName;
	}
	public void setWifeName(String wifeName) {
		this.wifeName = wifeName;
	}
	public Husband getHusband() {
		return husband;
	}
	public void setHusband(Husband husband) {
		this.husband = husband;
	}

	


}

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
	<class name="OneToOneDouble.Husband" table="husband">
		<id name="Id">
      <!-- 主鍵來源wife,也就是共享的主鍵 -->  
			<generator class="foreign">
			<param name="property">wife</param>
			</generator>
		</id>
		<property name="husbanName" />
		<!-- constrained放錯位置會導致外來鍵死鎖 -->
		<one-to-one name="wife" class="OneToOneDouble.Wife"  constrained="true"/>


	</class>
</hibernate-mapping>
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
	<class name="OneToOneDouble.Wife" table="wife">
		<id name="Id">
			<generator class="native"></generator>
		</id>
		<property name="wifeName" />
		
		<one-to-one name="husband" class="OneToOneDouble.Husband" ></one-to-one>

	
	</class>
</hibernate-mapping>

3單向【1-N】

從N-1反過來,由Teacher物件維護多個Student物件的管理。
只需要在【1】方新增對【N】方Set集合型別屬性為Student的雜湊set集合。

但是【不需要!】在【N】方定義Teacher屬性。

外來鍵依然是屬於【N】方的。
在持久化類中通過重寫hashCode和equals方法來實現對持久化物件的比較,如果兩個物件的識別符號相等即對應資料庫同一條記錄,

那麼Hibernate就會把兩個物件看作同一個物件。

package OneToManySingle;

public class Student {
	private String studentName;
	private Integer studentId;
	private String studentSex;

	public String getStudentName() {
		return studentName;
	}

	public void setStudentName(String studentName) {
		this.studentName = studentName;
	}

	public Integer getStudentId() {
		return studentId;
	}

	public void setStudentId(Integer studentId) {
		this.studentId = studentId;
	}

	public String getStudentSex() {
		return studentSex;
	}

	public void setStudentSex(String studentSex) {
		this.studentSex = studentSex;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((studentId == null) ? 0 : studentId.hashCode());
		return result;
	}

	public Student() {
		// TODO Auto-generated constructor stub
	}

	

}
package OneToManySingle;

import java.util.HashSet;
import java.util.Set;

public class Teacher {
	private Integer teacherId;
	private String teacherName;
	private Integer teacherAge;

	private Set<Student> students = new HashSet<Student>();

	public Integer getTeacherId() {
		return teacherId;
	}

	public void setTeacherId(Integer teacherId) {
		this.teacherId = teacherId;
	}

	public String getTeacherName() {
		return teacherName;
	}

	public void setTeacherName(String teacherName) {
		this.teacherName = teacherName;
	}

	public Integer getTeacherAge() {
		return teacherAge;
	}

	public void setTeacherAge(Integer teacherAge) {
		this.teacherAge = teacherAge;
	}

	public Set<Student> getStudents() {
		return students;
	}

	public void setStudents(Set<Student> students) {
		this.students = students;
	}

}
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<!-- javabean與表的對映關係 -->
<hibernate-mapping>
	<class name="OneToManySingle.Student" table="student">
		<!-- 主鍵對應 -->
		<id name="studentId">
			<generator class="native"></generator>
		</id>
		<property name="studentName" />
		<property name="studentSex"></property>

	</class>
</hibernate-mapping>
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<!-- javabean與表的對映關係 -->
<hibernate-mapping>
	<class name="OneToManySingle.Teacher" table="teacher">
		<!-- 主鍵對應 -->
		<id name="teacherId">
			<generator class="native"></generator>
		</id>
		<property name="teacherName" />
		<property name="teacherAge"></property>
		
		<set name="students">
		<key column="teache_id"></key><!-- 外來鍵 -->
		<one-to-many class="OneToManySingle.Student"/>
		</set>
		

	</class>
</hibernate-mapping>

4雙向【1-N】

就是【單向1-N】和【單向N-1】的整合。
【N】方存在【1】方屬性,【1】放存放【N】方的set集合。

在實際開發中經常使用。

package OneToManyDouble;

import java.util.HashSet;
import java.util.Set;

/*與Linkman建立一對多關係.
 * 一個客戶可以有多個聯絡人
 * linkman表的外來鍵是cus_id;
 * */

public class Customer {
	private Integer cus_id;
	private String cus_name;
	private String cus_phone;

	private Set<Linkman> linkmans = new HashSet<Linkman>();

	public Set<Linkman> getLinkmans() {
		return linkmans;
	}

	public void setLinkmans(Set<Linkman> linkmans) {
		this.linkmans = linkmans;
	}

	public Integer getCus_id() {
		return cus_id;
	}

	public void setCus_id(Integer cus_id) {
		this.cus_id = cus_id;
	}

	public String getCus_name() {
		return cus_name;
	}

	public void setCus_name(String cus_name) {
		this.cus_name = cus_name;
	}

	public String getCus_phone() {
		return cus_phone;
	}

	public void setCus_phone(String cus_phone) {
		this.cus_phone = cus_phone;
	}

}
package OneToManyDouble;

public class Linkman {
	private Integer link_id;
	private String link_name;
	private String link_sex;
	
	
	private Customer customer;
	
	
	public Customer getCustomer() {
		return customer;
	}
	public void setCustomer(Customer customer) {
		this.customer = customer;
	}
	public Integer getLink_id() {
		return link_id;
	}
	public void setLink_id(Integer link_id) {
		this.link_id = link_id;
	}
	public String getLink_name() {
		return link_name;
	}
	public void setLink_name(String link_name) {
		this.link_name = link_name;
	}
	public String getLink_sex() {
		return link_sex;
	}
	public void setLink_sex(String link_sex) {
		this.link_sex = link_sex;
	}
	

}
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<!-- javabean與表的對映關係 -->
<hibernate-mapping>
	<class name="OneToManyDouble.Customer" table="customer">
		<!-- 主鍵對應 -->
		<id name="cus_id">
			<generator class="native"></generator>
		</id>
		<property name="cus_name" />
		<property name="cus_phone"></property>

		<!-- 設定與多方的關係 -->
		<set name="linkmans">
			<key column="link_cus_id"></key>
			<one-to-many class="OneToManyDouble.Linkman" />
		</set>




	</class>
</hibernate-mapping>
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
	<class name="OneToManyDouble.Linkman" table="linkman">
		<!-- 主鍵對應 -->
		<id name="link_id">
			<generator class="native"></generator>
		</id>
		<property name="link_name" />
		<property name="link_sex"></property>
		<!-- 建立多方 和 指定外來鍵 -->
		<many-to-one name="customer" class="OneToManyDouble.Customer"
			column="link_cus_id" />
	</class>
</hibernate-mapping>

5單向【N-1】

單向的【N-1】關聯只能從【N】的一端訪問【1】的一端。
一個買家對應多個訂單。
只需要在Order中定義一個Buyer型別的屬性,而不需要在Buyer中定義存放Order物件的集合屬性。
注意mysql裡order屬於關鍵字,最好改名。

package ManyToOneSingle;

public class Buyer {
	private Integer buyerId;
	private String buyerName;
	private String password;

	public Buyer() {

	}

	

	public Integer getBuyerId() {
		return buyerId;
	}

	public void setBuyerId(Integer buyerId) {
		this.buyerId = buyerId;
	}

	public String getBuyerName() {
		return buyerName;
	}

	public void setBuyerName(String buyerName) {
		this.buyerName = buyerName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

}
package ManyToOneSingle;

public class Order {

	private Integer orderId;
	private String orderNo;
	private Buyer buyer;

	public Integer getOrderId() {
		return orderId;
	}

	public void setOrderId(Integer orderId) {
		this.orderId = orderId;
	}

	public String getOrderNo() {
		return orderNo;
	}

	public void setOrderNo(String orderNo) {
		this.orderNo = orderNo;
	}

	public Buyer getBuyer() {
		return buyer;
	}

	public void setBuyer(Buyer buyer) {
		this.buyer = buyer;
	}

}

6單向【N-N】

每個N-N的實質都存在一箇中間表。
只有主動方物件關聯被動方物件,而被動方物件沒有關聯主動方物件。
此例子中Form是主動發,product是被動方。
一個Form物件可以包含一個或者多個不同的Product物件,
而同一個Product物件可以被0個或者多個不同的Order物件所包含。
主動方的配置中:
set的table屬性指明瞭兩個物件間連線表的表名。
key用於連線表中這隻關於form【主動方】的外來鍵和外來鍵名。
manytomany中的column屬性用於設定連線表引用自【被動方】product的外來鍵和外來鍵名。

package ManyToManySingle;

import java.util.HashSet;
import java.util.Set;

public class Form {
	private Integer formId;
	private String formName;
	private Set<Product> products = new HashSet<Product>();

	public Integer getFormId() {
		return formId;
	}

	public void setFormId(Integer formId) {
		this.formId = formId;
	}

	public String getFormName() {
		return formName;
	}

	public void setFormName(String formName) {
		this.formName = formName;
	}

	public Set<Product> getProducts() {
		return products;
	}

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

}
package ManyToManySingle;

public class Product {
	private Integer productId;
	private String productName;
	public Integer getProductId() {
		return productId;
	}
	public void setProductId(Integer productId) {
		this.productId = productId;
	}
	public String getProductName() {
		return productName;
	}
	public void setProductName(String productName) {
		this.productName = productName;
	}

}
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
	<class name="ManyToManySingle.Form" table="form">
		<id name="formId">
			<generator class="native"></generator>
		</id>
		<property name="formName" />
		
		<!-- table表示中間表 -->
		<set name="products" table="formitem">
		<key column="form_id"/>
		<!-- 設定了連線表中引用Product的外來鍵名為product_id -->
		<many-to-many class="ManyToManySingle.Product" column="product_id"></many-to-many>
		</set>

	


	</class>
</hibernate-mapping>
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
	<class name="ManyToManySingle.Product" table="product">
		<id name="productId">
			<generator class="native"></generator>
		</id>
		<property name="productName" />

	


	</class>
</hibernate-mapping>

7雙向【N-N】

主動方和被動方相互關聯。
兩方都有set集合。
要任選一方放棄外來鍵維護防止衝突。
package ManyToManyDouble;

import java.util.HashSet;
import java.util.Set;

public class People {
	private Integer peopleId;
	private String peopleName;
	private Set<Role> roles = new HashSet<Role>();//這裡一定要new出來。
	public Integer getPeopleId() {
		return peopleId;
	}
	public void setPeopleId(Integer peopleId) {
		this.peopleId = peopleId;
	}
	public String getPeopleName() {
		return peopleName;
	}
	public void setPeopleName(String peopleName) {
		this.peopleName = peopleName;
	}
	public Set<Role> getRoles() {
		return roles;
	}
	public void setRoles(Set<Role> roles) {
		this.roles = roles;
	}
	

}

package ManyToManyDouble;

import java.util.HashSet;
import java.util.Set;

public class Role {
	private Integer roleId;
	private String roleName;
	private Set<People> peoples = new HashSet<People>();

	public Integer getRoleId() {
		return roleId;
	}

	public void setRoleId(Integer roleId) {
		this.roleId = roleId;
	}

	public String getRoleName() {
		return roleName;
	}

	public void setRoleName(String roleName) {
		this.roleName = roleName;
	}

	public Set<People> getPeoples() {
		return peoples;
	}

	public void setPeoples(Set<People> peoples) {
		this.peoples = peoples;
	}

}
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
	<class name="ManyToManyDouble.People" table="People">
		<id name="peopleId">
			<generator class="native"></generator>
		</id>
		<property name="peopleName" />

		<set name="roles" table="roleitem" inverse="true">
			<key column="people_id" />
			<many-to-many class="ManyToManyDouble.Role" column="role_id" />
		</set>


	</class>
</hibernate-mapping>
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
	<class name="ManyToManyDouble.Role" table="Role">
		<id name="roleId">
			<generator class="native"></generator>
		</id>
		<property name="roleName" />

		<set name="peoples" table="roleitem">
			<key column="role_id" />
			<many-to-many class="ManyToManyDouble.People" column="people_id" />
		</set>

	</class>
</hibernate-mapping>

所有測試用例

package Test;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.yiki.util.Utils;

import OneToOneDouble.Husband;
import OneToOneDouble.Wife;

public class Double_1_1 {

	public static void main(String[] args) {
		Session session = Utils.openSession();
		Transaction tr = session.beginTransaction();
		Husband husband = new Husband();
		Wife wife = new Wife();
		
		husband.setHusbanName("o");
		wife.setWifeName("w");
		
		husband.setWife(wife);
		wife.setHusband(husband);
		
		session.save(wife);
		session.save(husband);
		
		tr.commit();
		
		session.close();
		
	
	
	}

}
package Test;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.yiki.util.Utils;

import OneToManyDouble.Customer;
import OneToManyDouble.Linkman;

public class Double_1_N {

	public static void main(String[] args) {
		Session session = Utils.openSession();
		Transaction tr = session.beginTransaction();
		Customer c1 = new Customer();
		Linkman link1 = new Linkman();
		link1.setLink_name("聯絡人1");
		Linkman link2 = new Linkman();
		link2.setLink_name("聯絡人2");
		c1.setCus_name("cus1");
		c1.setCus_phone("3333333");
	
		//雙向關聯
		c1.getLinkmans().add(link1);
		c1.getLinkmans().add(link2);
		link1.setCustomer(c1);
		link2.setCustomer(c1);
		
		session.save(c1);
		session.save(link1);
		session.save(link2);
		
		tr.commit();
		
		session.close();
		
		
		

	}

}

package Test;

import org.hibernate.Session;
import org.hibernate.Transaction;
import com.yiki.util.Utils;

import ManyToManyDouble.People;
import ManyToManyDouble.Role;

public class Double_N_N {

	public static void main(String[] args) {
		Session session = Utils.openSession();
		Transaction tr = session.beginTransaction();

		People p1 = new People();
		p1.setPeopleName("tiffany");
		People p2 = new People();
		p2.setPeopleName("yiki");
		People p3 = new People();
		p3.setPeopleName("penny");

		Role r1 = new Role();
		r1.setRoleName("engineer");
		Role r2 = new Role();
		r2.setRoleName("girl");
		Role r3 = new Role();
		r3.setRoleName("singer");

		p1.getRoles().add(r2);
		r2.getPeoples().add(p1);
		r2.getPeoples().add(p1);

		p2.getRoles().add(r3);
		r3.getPeoples().add(p2);
		
		p3.getRoles().add(r2);
		r2.getPeoples().add(p3);

		session.save(p1);
		session.save(p2);
		session.save(p3);
		session.save(r1);
		session.save(r2);
		session.save(r3);
		tr.commit();
		session.close();
	}

}

package Test;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.yiki.util.Utils;

import OneToOneSingle.User;
import OneToOneSingle.UserInfo;

public class single_1_1 {
	public static void main(String[] args) {
		Session session = Utils.openSession();
		Transaction tr = session.beginTransaction();

		User user = new User();
		UserInfo info = new UserInfo();
		info.setAddress("Chongqin");
		info.setMail("[email protected]");
		user.setUsername("tiffany");
		user.setPassword("22222");
		user.setUserinfo(info);
		
		session.save(user);
		session.save(info);
		
		tr.commit();
		session.close();

	}

}
package Test;

import org.hibernate.Session;
import org.hibernate.Transaction;
import com.yiki.util.Utils;
import OneToManySingle.Student;
import OneToManySingle.Teacher;

public class Single_1_N {

	public static void main(String[] args) {
		Session session = Utils.openSession();
		Transaction tr = session.beginTransaction();

		Teacher teacher = new Teacher();
		Student s1 = new Student();
		Student s2 = new Student();

		teacher.setTeacherName("老師1");
		teacher.setTeacherAge(34);
		s1.setStudentName("yi");
		s1.setStudentSex("male");
		s2.setStudentName("ki");
		s2.setStudentSex("female");

		teacher.getStudents().add(s1);
		teacher.getStudents().add(s2);

		session.save(s1);
		session.save(s2);
		session.save(teacher);
		tr.commit();
		session.close();
	}

}

package Test;

import org.hibernate.Session;
import org.hibernate.Transaction;
import com.yiki.util.Utils;
import ManyToOneSingle.Buyer;
import ManyToOneSingle.Order;
public class Single_N_1 {
	
	
	public static void main(String[] args) {
		addBuyerAndOrder();
		
	}
	public static void addBuyerAndOrder(){
		Buyer buyer = new Buyer();
		buyer.setBuyerName("tiffany");
		buyer.setPassword("123344");
		addBuyer(buyer);
		
		Order order = new Order();
		order.setBuyer(buyer);
		order.setOrderNo("2");
		addOrder(order);
		
		
	} 
	
	private static void addOrder(Order order) {
		Session session = Utils.openSession();
		Transaction tr = session.beginTransaction();
		session.save(order);
		tr.commit();
		session.close();
		
	}
	private static void addBuyer(Buyer buyer) {
		Session session = Utils.openSession();
		Transaction tr = session.beginTransaction();
		session.save(buyer);
		tr.commit();
		session.close();
		
	}
	

}
package Test;

import org.hibernate.Session;
import org.hibernate.Transaction;
import com.yiki.util.Utils;
import ManyToManySingle.Form;
import ManyToManySingle.Product;
public class Single_N_N {
	
	
	public static void main(String[] args) {
		Session session = Utils.openSession();
		Transaction tr = session.beginTransaction();
		
		Product p1 = new Product();
		Product p2 = new Product();
		
		Form f1 = new Form();
		Form f2 = new Form();
		
		p1.setProductName("產品1");
		p2.setProductName("產品2");
		f1.setFormName("訂單1");
		f2.setFormName("訂單2");
		
		f1.getProducts().add(p1);
		f1.getProducts().add(p2);
		f2.getProducts().add(p1);
		
		
		
		
		session.save(p1);
		session.save(p2);
		session.save(f1);
		session.save(f2);
		tr.commit();
		session.close();
	}
	
	

}

會話池


package com.yiki.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/*
 * 工具包*/
@SuppressWarnings("deprecation")
public class Utils {

	public static final Configuration CFG;
	public static final SessionFactory FACTORY;

	// Configuration config = new Configuration();
	// config.configure();
	// serviceRegistry = new
	// ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
	// sessionFactory = config.buildSessionFactory(serviceRegistry);
	// Session session = sessionFactory.getCurrentSession();

	static {
		CFG = new Configuration().configure();
		FACTORY = CFG.buildSessionFactory();

	}

	public static Session openSession() {
		return FACTORY.openSession();

	}

}












相關推薦

[Hibernate]關聯關係配置檔案測試例項

用了一天整理下來。所有關係分為以下七種:單向【1-1】雙向【1-1】單向【1-N】雙向【1-N】單向【N-1】單向【N-N】雙向【N-N】1單向【1-1】基於外來鍵的單向【1-1】是【N-1】的特殊形式,要求【N】方唯一。基於外來鍵的單向1-1只需要在原有的<many-

redis cluster配置檔案叢集狀態

redis cluster命令 叢集(cluster)   cluster info       列印叢集的資訊 cluster nodes   列出叢集當前已知的所有節點(node),以及這些節點的相關資訊   節點(node)   cluster meet <ip

Hibernate學習(3) (繼承對映,配置檔案註解版)

這篇blog準備寫怎樣在Hibernate中反應記憶體物件之間的繼承關係.我們知道,記憶體物件之間是可以有繼承關係的,但是在資料庫中,我們繼承神馬的都是浮雲,不存在的.那麼怎麼辦呢?Hibernate提供了繼承關係對映!(其實就是幫你把原來的一個類以一種特定的方

struts2 配置檔案中各個項

<action   name= "Login_* "   method= "{1} "   class= "mailreader2.Login "> 中Login_*帶*是什麼意思?method= "{1} "帶{}這個是什麼意

Nginx配置檔案nginx.conf中文

#定義Nginx執行的使用者和使用者組 user www www; #nginx程序數,建議設定為等於CPU總核心數。 worker_processes 8; #全域性錯誤日誌定義型別,[ debug | info | notice | warn

python configparser配置檔案解析器使用

configparser簡介 python2下該模組名為ConfigParser,到3才改為configparser,可以看官方ConfigParser模組的說明 ConfigParse 官方文件 python3中configparser模組的使用,confi

檔案管理系統 : 增加檔案的空間 增加swap檔案swap空間

增加home的空間 1、利用fdisk命令建立分割槽 2、建立擴充套件分割槽 3、p命令用於檢視所有分割槽,w命令儲存 4、vgextend +路徑,擴展卷組的容量 5、lvextend+路徑,擴充套件邏輯卷的容量 6、resize2fs 啟用lv

Nginx配置檔案nginx.conf中文(總結)

#定義Nginx執行的使用者和使用者組 user www www; #nginx程序數,建議設定為等於CPU總核心數。 worker_processes 8; #全域性錯誤日誌定義型別,[ debug | info | notice | warn | erro

Apache配置檔案及目錄結構學習整理

一、配置檔案 配置檔案預設分為3個部分 [[email protected] ~]# grep ‘<Section>’ /etc/httpd/conf/httpd.conf -Hn /etc/httpd/conf/httpd.conf:33

Reids配置檔案redis.conf中文

redis的各種配置都是在redis.conf檔案中進行配置的,有關其每項配置的中文詳細解釋如下。 對應的中文版解釋redis.conf : # Redis 配置檔案示例 # 注意單位: 當需要配置記憶體大小時, 可能需要指定像1k,5GB,4M等常見格式 # #

log4j2.x配置檔案中各標籤

log4j2.0以後我們通常在log4j2.xml中配置相關引數,在配置的時候我們需要理解這些引數的具體含義,下面列出了這些引數的解釋。 1、Logger 完成日誌資訊的處理 <logger name="com.srd.ljzd" level="I

MySQL配置檔案mysql.ini引數、MySQL效能優化

my.ini(Linux系統下是my.cnf),當mysql伺服器啟動時它會讀取這個檔案,設定相關的執行環境引數。 my.ini分為兩塊:Client Section和Server Section。 Client Section用來配置MySQL客戶端引數。 要檢視配置引

Android中BroadcastReceiver的兩註冊方式(靜態動態)

今天我們一起來探討下安卓中BroadcastReceiver元件以及詳細分析下它的兩種註冊方式。 BroadcastReceiver也就是“廣播接收者”的意思,顧名思義,它就是用來接收來自系統和應用中的廣播。在Android系統中,廣播體現在方方面面,例如當開機完成後系統會

linux kafka叢集配置測試圖文

一.前期準備 1.1 Win7官網下載kafka包 本文使用版本kafka_2.10-0.10.1.0.tgz 1.2 配置jdk、scala、zookeeper jdk,scala,

struts2配置檔案中method="{1}"

struts2為了簡化配置檔案,來採用了萬用字元的方式 圖中的method="{1}"指向的是action後的第一個萬用字元,也就是如圖的 * , 假如name中含有多個萬用字元 , 則method

caffe網路配置檔案欄位意義

解決方案:lenet_solver.prototxt # The train/test net protocol buffer definition net: "examples/mnist/lenet_train_test.prototxt" //網路協議具體定義 # t

nginx配置檔案中的location

一、location語法簡介及用法: URL地址匹配是Nginx配置中最靈活的部分.location 支援正則表示式匹配,也支援條件匹配,使用者可以通過location指令實現Nginx對動丶靜態網頁的過濾處理。 1.語法規則:  location [=|~|~*|^~]

linux shell 指令碼讀取 ini 配置檔案(命令部分

wanxiaoderen: 這句 判斷理解難度略高,查資料半天后,我來解釋下 (awk的使用(不瞭解的可以掃盲)http://blog.chinaunix.net/uid-23302288-id-3785105.html) ReadINI=`awk -F '=' '

Spring配置檔案中 註解標籤

<context:annotation-config/> 在基於主機方式配置Spring時,Spring配置檔案applicationContext.xml,你可能會見<context:annotation-config/>這樣一條配置

(總結)Nginx配置檔案nginx.conf中文

結合自己的使用經驗,把Nginx的主要配置引數說明分享一下,也參考了一些網路的內容,這篇是目前最完整的Nginx配置引數中文說明了。更詳細的模組引數請參考:http://wiki.nginx.org/Main #定義Nginx執行的使用者和使用者組 user www ww