Hibernate实例实现(注解方式)添加两张关系表

1.新建两个实体类Employee.class 和 Company.class


2.新建一个主配置文件 ec-hibernate.xml(注解的方式省去映射文件)




	
		com.mysql.jdbc.Driver
		jdbc:mysql://localhost:3306/test
		root
		408817
		org.hibernate.dialect.MySQL57Dialect
		true
		update
		
		
		
		
		


3.Employee.class

package com.jmx.ec;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import org.hibernate.annotations.CascadeType;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.GenericGenerator;

/**
 * 员工
 * */
@Entity //实体
@Table(name="employee") //表名
@GenericGenerator(name="genid",strategy="increment") //主键生成策略
public class Employee {
	@Id
	@GeneratedValue(generator="genid") //主键生成策略
	@Column(name="eid")
	private int eid;
	
	@Column(name="ename")
	private String ename;
	
	@ManyToOne
	@Cascade(value={CascadeType.SAVE_UPDATE})
	@JoinColumn(name="companyid")
	private Company company;
	
	public Company getCompany() {
		return company;
	}
	public void setCompany(Company company) {
		this.company = company;
	}
	public int getEid() {
		return eid;
	}
	public void setEid(int eid) {
		this.eid = eid;
	}
	public String getEname() {
		return ename;
	}
	public void setEname(String ename) {
		this.ename = ename;
	}
	
}



4.Company.class

package com.jmx.ec;

import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import org.hibernate.annotations.GenericGenerator;

/**
 * 公司
 * */
@Entity
@Table(name="company")
@GenericGenerator(name="genid", strategy="increment")
public class Company {
	@Id
	@GeneratedValue(generator="genid")
	@Column(name="cid")
	private int cid;
	
	@Column(name="cname")
	private String cname;

	@OneToMany
	@Cascade(value= {CascadeType.ALL})
	@JoinColumn(name="companyid")
	public Set employees;
	
	public int getCid() {
		return cid;
	}
	public void setCid(int cid) {
		this.cid = cid;
	}
	public String getCname() {
		return cname;
	}
	public void setCname(String cname) {
		this.cname = cname;
	}
	public Set getEmployees() {
		return employees;
	}
	public void setEmployees(Set employees) {
		this.employees = employees;
	}
}


最后编写一个测试类:

	//读取配置文件
	Configuration cfg =new Configuration();
	cfg.configure("ec-hibernate.xml");
	SessionFactory factory = cfg.buildSessionFactory();
	Session session = factory.openSession();
	Transaction transaction = session.beginTransaction();


执行后:




你可能感兴趣的:(Hibernate)