映射关系级别注解

映射关系级别注解

一对一单向外键

@OneToOne(cascade=CascadeType.ALL)

@JoinColumn(name="pid",unique=true)

注意:保存时应该先保存外键对象,在保存主表对象

实例:将环境配置好,所需要的包前边已经提到过,

学生实体类:

package com.oto;

import java.util.Date;

import javax.persistence.CascadeType;
import javax.persistence.Entity;//JPA注解
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;

/*
 * 学生实体类
 */
@Entity
public class Students {
         private int sid; //学号
         private IdCard card;//身份证
         private String gender;//性别
         private Date birthday;//出生日期
         private String major;//专业

         public Students(){

         }

		public Students(IdCard card,  String gender,
				Date date, String major) {
//			super();
			this.card = card;
			this.gender = gender;
			this.birthday = date;
			this.major = major;
		}
        @Id
        @GeneratedValue
        public int getSid() {
			return sid;
		}

		public void setSid(int sid) {
			this.sid = sid;
		}

		public String getGender() {
			return gender;
		}

		public void setGender(String gender) {
			this.gender = gender;
		}

		public Date getBirthday() {
			return birthday;
		}

		public void setBirthday(Date birthday) {
			this.birthday = birthday;
		}

		public String getMajor() {
			return major;
		}

		public void setMajor(String major) {
			this.major = major;
		}

		@OneToOne(cascade=CascadeType.ALL)
		@JoinColumn(name="pid",unique=true)
		public IdCard getCard() {
			return card;
		}

		public void setCard(IdCard card) {
			this.card = card;
		}

}

身份证实体类:

package com.oto;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

import org.hibernate.annotations.GenericGenerator;

@Entity
public class IdCard {
	     @Id
	     @GeneratedValue(generator="pid")
	     @GenericGenerator(name="pid",strategy="assigned")
	     @Column(length=18)
         private String pid; //身份证号
         private String sname;//姓名

         public IdCard(){

         }

		public IdCard(String pid, String sname) {
			this.pid = pid;
			this.sname = sname;
		}

		public String getPid() {
			return pid;
		}
		public void setPid(String pid) {
			this.pid = pid;
		}
		public String getSname() {
			return sname;
		}
		public void setSname(String sname) {
			this.sname = sname;
		}

}

测试类:

package com.oto;

import java.util.Date;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.Test;

public class TestStudents {
	@Test
    public void testShemaExport(){
 	   //创建hibernate配置对象
 	   Configuration config = new Configuration().configure();
 	   //创建服务注册对象
 	   ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
        //生成SessionFactory
 	   SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);
        SchemaExport export = new SchemaExport(config);
        export.create(true,true);
    }
	//往数据库中添加学生数据
	@Test
	public void addStudents(){
		  //创建hibernate配置对象
 	   Configuration config = new Configuration().configure();
 	   //创建服务注册对象
 	   ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
        //生成SessionFactory
 	   SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);
       //创建会话
 	   Session session = sessionFactory.getCurrentSession();
 	   //创建事务
 	   Transaction tx = session.beginTransaction();
 	   IdCard card = new IdCard("123456789012345678","猪八戒");
 	   Students stu = new Students(card,"男",new Date(),"计算机");
 	   session.save(card);
 	   session.save(stu);
 	   tx.commit();
	}
}

hibernate.cfg.xml中的配置:下面的使用的是同一个配置,下边的代码中不再列举,

<!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>
	<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
		<!--
		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="hibernate.connection.url">jdbc:mysql:///hibernate_struts_stumanager</property>
		 -->
		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mypage</property>

		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.connection.password">root</property>
		<property name="hibernate.show_sql">false</property>
		<property name="hibernate.hbm2ddl.auto">create</property>
		<property name="current_session_context_class">thread</property>
		<!-- <mapping class="com.oto.Students"/>
		<mapping class="com.oto.IdCard"/> --><!-- 一对一单向外键关联 -->

		<!-- <mapping class="com.oto_11.Students"/>
		<mapping class="com.oto_11.IdCard"/>  -->        <!--一对一双向外键关联  -->

		<!-- <mapping class="com.mto.Students"/>
		<mapping class="com.mto.ClassRoom"/> --><!--  多对一单向外键关联-->

		<!-- <mapping class="com.otm.Students"/>
		<mapping class="com.otm.ClassRoom"/> --><!-- 一对多单向外键关联 -->

		<!-- <mapping class="com.otm_11.Students"/>
		<mapping class="com.otm_11.ClassRoom"/> --><!-- 一对多双向外键 -->

		<!-- <mapping class="com.mtm.Students"/>
		<mapping class="com.mtm.Teachers"/>  --> <!-- 多对多单向外键关联 -->

		<mapping class="com.mtm_11.Students"/>
		<mapping class="com.mtm_11.Teachers"/>   <!-- 多对多双向外键关联 -->
	</session-factory>
</hibernate-configuration>

一对一双向外键关联

主控方的配置同一对一单向外键关联

@OneToOne(mappedBy="card")//被控方

双向关联,必须设置mappedBy属性。因为双向关联只能交给一方去控制,不可能在双方

都设置外键保存关联关系,否则双方都无法保存

实例:

学生实体类

package com.oto_11;

import java.util.Date;

import javax.persistence.CascadeType;
import javax.persistence.Entity;//JPA注解
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;

/*
 * 学生实体类
 */
@Entity
public class Students {
         private int sid; //学号
         private IdCard card;//身份证
         private String gender;//性别
         private Date birthday;//出生日期
         private String major;//专业

         public Students(){

         }

		public Students(IdCard card,  String gender,
				Date date, String major) {
//			super();
			this.card = card;
			this.gender = gender;
			this.birthday = date;
			this.major = major;
		}
        @Id
        @GeneratedValue
        public int getSid() {
			return sid;
		}

		public void setSid(int sid) {
			this.sid = sid;
		}

		public String getGender() {
			return gender;
		}

		public void setGender(String gender) {
			this.gender = gender;
		}

		public Date getBirthday() {
			return birthday;
		}

		public void setBirthday(Date birthday) {
			this.birthday = birthday;
		}

		public String getMajor() {
			return major;
		}

		public void setMajor(String major) {
			this.major = major;
		}

		@OneToOne(cascade=CascadeType.ALL)
		@JoinColumn(name="pid",unique=true)
		public IdCard getCard() {
			return card;
		}

		public void setCard(IdCard card) {
			this.card = card;
		}

}

身份证实体类:

package com.oto_11;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;

import org.hibernate.annotations.GenericGenerator;

@Entity
public class IdCard {
	     @Id
	     @GeneratedValue(generator="pid")
	     @GenericGenerator(name="pid",strategy="assigned")
	     @Column(length=18)
         private String pid; //身份证号
         private String sname;//姓名

         @OneToOne(mappedBy="card")
         private Students stu;

         public IdCard(){

         }

		public IdCard(String pid, String sname) {
			this.pid = pid;
			this.sname = sname;
		}

		public Students getStu() {
			return stu;
		}

		public void setStu(Students stu) {
			this.stu = stu;
		}

		public String getPid() {
			return pid;
		}
		public void setPid(String pid) {
			this.pid = pid;
		}
		public String getSname() {
			return sname;
		}
		public void setSname(String sname) {
			this.sname = sname;
		}

}

测试类:

package com.oto_11;

import java.util.Date;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.Test;

public class TestStudents {
	@Test
    public void testShemaExport(){
 	   //创建hibernate配置对象
 	   Configuration config = new Configuration().configure();
 	   //创建服务注册对象
 	   ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
        //生成SessionFactory
 	   SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);
        SchemaExport export = new SchemaExport(config);
        export.create(true,true);
    }
	@Test
	public void addStudents(){
		  //创建hibernate配置对象
 	   Configuration config = new Configuration().configure();
 	   //创建服务注册对象
 	   ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
        //生成SessionFactory
 	   SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);
       //创建会话
 	   Session session = sessionFactory.getCurrentSession();
 	   //创建事务
 	   Transaction tx = session.beginTransaction();
 	   IdCard card = new IdCard("123456789012345678","猪八戒");
 	   Students stu = new Students(card,"男",new Date(),"计算机");
 	   session.save(card);
 	   session.save(stu);
 	   tx.commit();
	}
}

一对一单向外键联合主键

一对一双向外键联合主键

创建主键类

主键类必须实现serializable接口,重写hashCode()和equals()方法。

主键类

@Embeddable

实体类

@EmbeddedId

多对一单向外键关联

多方持有一方的引用

@ManyToOne(cascade={CascadeType.ALL},

fetch=FetchType.EAGER)

@JoinColumn(name="cid",referencedColumnName="CID")

学生实体类:

package com.mto;

import java.util.Date;

import javax.persistence.CascadeType;
import javax.persistence.Entity;//JPA注解
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;

/*
 * 学生实体类
 */
@Entity
public class Students {
         private int sid; //学号
         private String gender;//性别
         private Date birthday;//出生日期
         private String major;//专业
         private ClassRoom classroom;
         private String sname;

         public Students(){

         }

		public Students(String sname,  String gender,
				Date date, String major) {
//			super();
            this.sname = sname;
			this.gender = gender;
			this.birthday = date;
			this.major = major;
		}
        @Id
        @GeneratedValue
        public int getSid() {
			return sid;
		}

		public void setSid(int sid) {
			this.sid = sid;
		}

		public String getSname() {
			return sname;
		}

		public void setSname(String sname) {
			this.sname = sname;
		}

		public String getGender() {
			return gender;
		}

		public void setGender(String gender) {
			this.gender = gender;
		}

		public Date getBirthday() {
			return birthday;
		}

		public void setBirthday(Date birthday) {
			this.birthday = birthday;
		}

		public String getMajor() {
			return major;
		}

		public void setMajor(String major) {
			this.major = major;
		}
		@ManyToOne(cascade={CascadeType.ALL},fetch=FetchType.EAGER)
		@JoinColumn(name="cid",referencedColumnName="CID")
		public ClassRoom getClassroom() {
			return classroom;
		}

		public void setClassroom(ClassRoom classroom) {
			this.classroom = classroom;
		}

}

班级实体类:

package com.mto;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

import org.hibernate.annotations.GenericGenerator;

//班级实体类
@Entity
public class ClassRoom {
	   @Id
	   @GeneratedValue(generator="cid")
	   @GenericGenerator(name="cid",strategy="assigned")
	   @Column(length=4)
       private String cid;//班级的编号
       private String cname;//班级的名字

       public ClassRoom(){

       }

	public ClassRoom(String cid, String cname) {
		this.cid = cid;
		this.cname = cname;
	}

	public String getCid() {
		return cid;
	}
	public void setCid(String cid) {
		this.cid = cid;
	}
	public String getCname() {
		return cname;
	}
	public void setCname(String cname) {
		this.cname = cname;
	}

}

测试类:

package com.mto;

import java.util.Date;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.Test;

public class TestStudents {
	@Test
    public void testShemaExport(){
 	   //创建hibernate配置对象
 	   Configuration config = new Configuration().configure();
 	   //创建服务注册对象
 	   ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
        //生成SessionFactory
 	   SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);
        SchemaExport export = new SchemaExport(config);
        export.create(true,true);
    }
	//往数据库中添加学生数据
	@Test
	public void addStudents(){
		  //创建hibernate配置对象
 	   Configuration config = new Configuration().configure();
 	   //创建服务注册对象
 	   ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
        //生成SessionFactory
 	   SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);
       //创建会话
 	   Session session = sessionFactory.getCurrentSession();
 	   //创建事务
 	   Transaction tx = session.beginTransaction();
       //创建班级对象
 	   ClassRoom c1 = new ClassRoom("0001","软件工程");
 	   ClassRoom c2 = new ClassRoom("0002","通信工程");
 	   //创建学生对象
 	   Students s1 = new Students("小王","男",new Date(),"计算机");
 	   Students s2 = new Students("小黄","男",new Date(),"计算机");
 	   Students s3 = new Students("小花","女",new Date(),"计算机");
 	   Students s4 = new Students("小红","女",new Date(),"计算机");

 	   s1.setClassroom(c1);
 	   s2.setClassroom(c1);

 	   s3.setClassroom(c2);
 	   s4.setClassroom(c2);

 	   session.save(c1);
 	   session.save(c2);
 	   session.save(s1);
 	   session.save(s2);
 	   session.save(s3);
 	   session.save(s4);
      tx.commit();
	}
}

一对多单向外键关联

一方持有多方的集合

@OneToMany(cascade={cascadeType.ALL},fetch=FetchType.LAZY)

@JoinColumn(name="cid")

实例:

学生实体类:

package com.otm;

import java.util.Date;

import javax.persistence.CascadeType;
import javax.persistence.Entity;//JPA注解
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;

/*
 * 学生实体类
 */
@Entity
public class Students {
         private int sid; //学号
         private String gender;//性别
         private Date birthday;//出生日期
         private String major;//专业
         private String sname;

         public Students(){

         }

		public Students(String sname,  String gender,
				Date date, String major) {
//			super();
            this.sname = sname;
			this.gender = gender;
			this.birthday = date;
			this.major = major;
		}
        @Id
        @GeneratedValue
        public int getSid() {
			return sid;
		}

		public void setSid(int sid) {
			this.sid = sid;
		}

		public String getSname() {
			return sname;
		}

		public void setSname(String sname) {
			this.sname = sname;
		}

		public String getGender() {
			return gender;
		}

		public void setGender(String gender) {
			this.gender = gender;
		}

		public Date getBirthday() {
			return birthday;
		}

		public void setBirthday(Date birthday) {
			this.birthday = birthday;
		}

		public String getMajor() {
			return major;
		}

		public void setMajor(String major) {
			this.major = major;
		}

}

班级实体类:

package com.otm;

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.JoinColumn;
import javax.persistence.OneToMany;

import org.hibernate.annotations.GenericGenerator;

//班级实体类
@Entity
public class ClassRoom {
	   @Id
	   @GeneratedValue(generator="cid")
	   @GenericGenerator(name="cid",strategy="assigned")
	   @Column(length=4)
       private String cid;//班级的编号
       private String cname;//班级的名字

       @OneToMany(cascade={CascadeType.ALL},fetch=FetchType.LAZY)
	   @JoinColumn(name="cid")
       private Set<Students> stus;//一方持有多方的集合
       public ClassRoom(){

       }

	public ClassRoom(String cid, String cname) {
		this.cid = cid;
		this.cname = cname;
	}

	public String getCid() {
		return cid;
	}
	public void setCid(String cid) {
		this.cid = cid;
	}
	public String getCname() {
		return cname;
	}
	public void setCname(String cname) {
		this.cname = cname;
	}

	public Set<Students> getStus() {
		return stus;
	}

	public void setStus(Set<Students> stus) {
		this.stus = stus;
	}

}

测试类:

package com.otm;

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

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.Test;

public class TestStudents {
	@Test
    public void testShemaExport(){
 	   //创建hibernate配置对象
 	   Configuration config = new Configuration().configure();
 	   //创建服务注册对象
 	   ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
        //生成SessionFactory
 	   SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);
        SchemaExport export = new SchemaExport(config);
        export.create(true,true);
    }
	@Test
	public void addStudents(){
		  //创建hibernate配置对象
 	   Configuration config = new Configuration().configure();
 	   //创建服务注册对象
 	   ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
        //生成SessionFactory
 	   SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);
       //创建会话
 	   Session session = sessionFactory.getCurrentSession();
 	   //创建事务
 	   Transaction tx = session.beginTransaction();
       //创建班级对象
 	   ClassRoom c1 = new ClassRoom("0001","软件工程");
 	   ClassRoom c2 = new ClassRoom("0002","通信工程");
 	   //创建学生对象
 	   Students s1 = new Students("小王","男",new Date(),"计算机");
 	   Students s2 = new Students("小黄","男",new Date(),"计算机");
 	   Students s3 = new Students("小花","女",new Date(),"计算机");
 	   Students s4 = new Students("小红","女",new Date(),"计算机");

 	   Set<Students> set1 = new HashSet<Students>();
 	   set1.add(s1);
 	   set1.add(s2);

 	   Set<Students> set2 = new HashSet<Students>();
 	   set2.add(s3);
 	   set2.add(s4);

 	   session.save(s1);
 	   session.save(s2);
 	   session.save(s3);
 	   session.save(s4);

 	   session.save(c1);
 	   session.save(c2);
      tx.commit();
	}
}

一对多双向外键关联

多方:多方持有一方的引用

@ManyToOne(cascade={CascadeType.ALL},fetch=FetchType.EAGER)

@JoinColumn(name="cid")

一方:一方持有多方的集合

@OneToMany(cascade={CascadeType.ALL},fetch=FetchType.LAZY)

@JoinColumn(name="cid")

实例:

package com.otm_11;

import java.util.Date;

import javax.persistence.CascadeType;
import javax.persistence.Entity;//JPA注解
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;

/*
 * 学生实体类
 */
@Entity
public class Students {
         private int sid; //学号
         private String gender;//性别
         private Date birthday;//出生日期
         private String major;//专业
         private String sname;//姓名
         private ClassRoom classroom;
         public Students(){

         }

		public Students(String sname,  String gender,
				Date date, String major) {
//			super();
            this.sname = sname;
			this.gender = gender;
			this.birthday = date;
			this.major = major;
		}
        @Id
        @GeneratedValue
        public int getSid() {
			return sid;
		}

		public void setSid(int sid) {
			this.sid = sid;
		}

		public String getSname() {
			return sname;
		}

		public void setSname(String sname) {
			this.sname = sname;
		}

		public String getGender() {
			return gender;
		}

		public void setGender(String gender) {
			this.gender = gender;
		}

		public Date getBirthday() {
			return birthday;
		}

		public void setBirthday(Date birthday) {
			this.birthday = birthday;
		}

		public String getMajor() {
			return major;
		}

		public void setMajor(String major) {
			this.major = major;
		}
		@ManyToOne(cascade={CascadeType.ALL},fetch=FetchType.EAGER)
		@JoinColumn(name="cid")
		public ClassRoom getClassroom() {
			return classroom;
		}

		public void setClassroom(ClassRoom classroom) {
			this.classroom = classroom;
		}

}

班级实体类:

package com.otm_11;

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.JoinColumn;
import javax.persistence.OneToMany;

import org.hibernate.annotations.GenericGenerator;

//班级实体类
@Entity
public class ClassRoom {
	   @Id
	   @GeneratedValue(generator="cid")
	   @GenericGenerator(name="cid",strategy="assigned")
	   @Column(length=4)
       private String cid;//班级的编号
       private String cname;//班级的名字

       @OneToMany(cascade={CascadeType.ALL},fetch=FetchType.LAZY)
	   @JoinColumn(name="cid")
       private Set<Students> stus;//一方持有多方的集合
       public ClassRoom(){

       }

	public ClassRoom(String cid, String cname) {
		this.cid = cid;
		this.cname = cname;
	}

	public String getCid() {
		return cid;
	}
	public void setCid(String cid) {
		this.cid = cid;
	}
	public String getCname() {
		return cname;
	}
	public void setCname(String cname) {
		this.cname = cname;
	}

	public Set<Students> getStus() {
		return stus;
	}

	public void setStus(Set<Students> stus) {
		this.stus = stus;
	}

}

测试类:

package com.mto_11;

import java.util.Date;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.Test;

import com.otm_11.ClassRoom;
import com.otm_11.Students;

public class TestStudents {
	@Test
    public void testShemaExport(){
 	   //创建hibernate配置对象
 	   Configuration config = new Configuration().configure();
 	   //创建服务注册对象
 	   ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
        //生成SessionFactory
 	   SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);
        SchemaExport export = new SchemaExport(config);
        export.create(true,true);
    }
	@Test
	public void addStudents(){
		  //创建hibernate配置对象
 	   Configuration config = new Configuration().configure();
 	   //创建服务注册对象
 	   ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
        //生成SessionFactory
 	   SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);
       //创建会话
 	   Session session = sessionFactory.getCurrentSession();
 	   //创建事务
 	   Transaction tx = session.beginTransaction();
       //创建班级对象
 	   ClassRoom c1 = new ClassRoom("0001","软件工程");
 	   ClassRoom c2 = new ClassRoom("0002","通信工程");
 	   //创建学生对象
 	   Students s1 = new Students("小王","男",new Date(),"计算机");
 	   Students s2 = new Students("小黄","男",new Date(),"计算机");
 	   Students s3 = new Students("小花","女",new Date(),"计算机");
 	   Students s4 = new Students("小红","女",new Date(),"计算机");

 	   s1.setClassroom(c1);
 	   s2.setClassroom(c1);

 	   s3.setClassroom(c2);
 	   s4.setClassroom(c2);

 	   session.save(c1);
 	   session.save(c2);
 	   session.save(s1);
 	   session.save(s2);
 	   session.save(s3);
 	   session.save(s4);
      tx.commit();
	}
}

多对多单向外键关联

其中一个多方持有另一个多方的集合对象

创建中间表

@MantToMany

@JoinTable(

name="teachers_students",

joinColumns={@JoinColumn(name="sid")},inverseJoinColumns={@JoinColumn(name="tid")}

)

实例:

学生实体类:

package com.mtm;

import java.util.Date;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Entity;//JPA注解
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;

/*
 * 学生实体类
 */
@Entity
public class Students {
         private int sid; //学号
         private String gender;//性别
         private Date birthday;//出生日期
         private String major;//专业
         private String sname;//学生姓名
         private Set<Teachers> teachers; //学生持有教师的集合

         public Students(){

         }

		public Students(String sname,  String gender,
				Date date, String major) {
//			super();
            this.sname = sname;
			this.gender = gender;
			this.birthday = date;
			this.major = major;
		}
        @Id
        @GeneratedValue
        public int getSid() {
			return sid;
		}

		public void setSid(int sid) {
			this.sid = sid;
		}

		public String getSname() {
			return sname;
		}

		public void setSname(String sname) {
			this.sname = sname;
		}

		public String getGender() {
			return gender;
		}

		public void setGender(String gender) {
			this.gender = gender;
		}

		public Date getBirthday() {
			return birthday;
		}

		public void setBirthday(Date birthday) {
			this.birthday = birthday;
		}

		public String getMajor() {
			return major;
		}

		public void setMajor(String major) {
			this.major = major;
		}
		 @ManyToMany
		  @JoinTable(
		      name="teachers_students",
		      joinColumns={@JoinColumn(name="sid")},
		      inverseJoinColumns={@JoinColumn(name="tid")}
		  )
		public Set<Teachers> getTeachers() {
			return teachers;
		}

		public void setTeachers(Set<Teachers> teachers) {
			this.teachers = teachers;
		}

}

老师实体类:

package com.mtm;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

import org.hibernate.annotations.GenericGenerator;

//教师实体类
@Entity
public class Teachers {
	      @Id
	      @GeneratedValue(generator="tid")
	      @GenericGenerator(name="tid",strategy="assigned")
	      @Column(length=4)
          private String tid;//教师id
          private String tname;//教师名字

          public Teachers(){

          }

		public Teachers(String tid, String tname) {
//			super();
			this.tid = tid;
			this.tname = tname;
		}

		public String getTid() {
			return tid;
		}
		public void setTid(String tid) {
			this.tid = tid;
		}
		public String getTname() {
			return tname;
		}
		public void setTname(String tname) {
			this.tname = tname;
		}

}

测试类:

package com.mtm;

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

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.Test;

public class TestStudents {
	@Test
    public void testShemaExport(){
 	   //创建hibernate配置对象
 	   Configuration config = new Configuration().configure();
 	   //创建服务注册对象
 	   ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
        //生成SessionFactory
 	   SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);
        SchemaExport export = new SchemaExport(config);
        export.create(true,true);
    }
	@Test
	public void addStudents(){
		 //创建hibernate配置对象
	 	   Configuration config = new Configuration().configure();
	 	   //创建服务注册对象
	 	   ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
	        //生成SessionFactory
	 	   SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);
	 	   Session session = sessionFactory.getCurrentSession();
	 	   Transaction tx = session.beginTransaction();

	 	   //创建教师对象
	 	   Teachers t1 = new Teachers("0001","张老师");
	 	   Teachers t2 = new Teachers("0002","黄老师");
	 	   Teachers t3 = new Teachers("0003","李老师");
	 	   Teachers t4 = new Teachers("0004","王老师");

	 	   Students s1 = new Students("张三","男",new Date(),"计算机");
	 	   Students s2 = new Students("李四","男",new Date(),"计算机");
	 	   Students s3 = new Students("王五","女",new Date(),"通信");
	 	   Students s4 = new Students("赵六","女",new Date(),"通信");

	 	   Set<Teachers> set1 = new HashSet<Teachers>();
	 	   set1.add(t1);
	 	   set1.add(t2);

	 	   Set<Teachers> set2 = new HashSet<Teachers>();
	 	   set2.add(t3);
	 	   set2.add(t4);

	 	   Set<Teachers> set3 = new HashSet<Teachers>();
	 	   set3.add(t1);
	 	   set3.add(t3);
	 	   set3.add(t4);

	 	   Set<Teachers> set4 = new HashSet<Teachers>();
	 	   set4.add(t2);
	 	   set4.add(t3);
	 	   set4.add(t4);

	 	   s1.setTeachers(set1);
	 	   s2.setTeachers(set2);
	 	   s3.setTeachers(set3);
	 	   s4.setTeachers(set4);

	 	   session.save(t1);
	 	   session.save(t2);
	 	   session.save(t3);
	 	   session.save(t4);

	 	   session.save(s1);
	 	   session.save(s2);
	 	   session.save(s3);
	 	   session.save(s4);

	 	   tx.commit();
	}
}

多对多双向外键关联

双方持有对方的集合对象,其中一方设置

//教师类

@ManyToMany(mappedBy="teachers")

另一方

//学生类

@ManyToMany

@JoinTable(

name="teachers_students",

joinColumns={@JoinColumn(name="sid")},

inverseJoinColumns={@JoinColumn(name="tid")}

)

实例:

学生实体类:

package com.mtm_11;

import java.util.Date;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Entity;//JPA注解
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;

/*
 * 学生实体类
 */
@Entity
public class Students {
         private int sid; //学号
         private String gender;//性别
         private Date birthday;//出生日期
         private String major;//专业
         private String sname;//学生姓名
         private Set<Teachers> teachers; //学生持有教师的集合

         public Students(){

         }

		public Students(String sname,  String gender,
				Date date, String major) {
//			super();
            this.sname = sname;
			this.gender = gender;
			this.birthday = date;
			this.major = major;
		}
        @Id
        @GeneratedValue
        public int getSid() {
			return sid;
		}

		public void setSid(int sid) {
			this.sid = sid;
		}

		public String getSname() {
			return sname;
		}

		public void setSname(String sname) {
			this.sname = sname;
		}

		public String getGender() {
			return gender;
		}

		public void setGender(String gender) {
			this.gender = gender;
		}

		public Date getBirthday() {
			return birthday;
		}

		public void setBirthday(Date birthday) {
			this.birthday = birthday;
		}

		public String getMajor() {
			return major;
		}

		public void setMajor(String major) {
			this.major = major;
		}
		 @ManyToMany
		  @JoinTable(
		      name="teachers_students",
		      joinColumns={@JoinColumn(name="sid")},
		      inverseJoinColumns={@JoinColumn(name="tid")}
		  )
		public Set<Teachers> getTeachers() {
			return teachers;
		}

		public void setTeachers(Set<Teachers> teachers) {
			this.teachers = teachers;
		}

}

老师实体类:

package com.mtm_11;

import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;

import org.hibernate.annotations.GenericGenerator;

//教师实体类
@Entity
public class Teachers {
	      @Id
	      @GeneratedValue(generator="tid")
	      @GenericGenerator(name="tid",strategy="assigned")
	      @Column(length=4)
          private String tid;//教师id
          private String tname;//教师名字

          @ManyToMany(mappedBy="teachers")
          private Set<Students> stus;//教师持有学生的集合

          public Teachers(){

          }

		public Teachers(String tid, String tname) {
//			super();
			this.tid = tid;
			this.tname = tname;
		}

		public String getTid() {
			return tid;
		}
		public void setTid(String tid) {
			this.tid = tid;
		}
		public String getTname() {
			return tname;
		}
		public void setTname(String tname) {
			this.tname = tname;
		}

}

测试类:

package com.mtm_11;

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

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.Test;

public class TestStudents {
	@Test
    public void testShemaExport(){
 	   //创建hibernate配置对象
 	   Configuration config = new Configuration().configure();
 	   //创建服务注册对象
 	   ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
        //生成SessionFactory
 	   SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);
        SchemaExport export = new SchemaExport(config);
        export.create(true,true);
    }
	@Test
	public void addStudents(){
		 //创建hibernate配置对象
	 	   Configuration config = new Configuration().configure();
	 	   //创建服务注册对象
	 	   ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
	        //生成SessionFactory
	 	   SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);
	 	   Session session = sessionFactory.getCurrentSession();
	 	   Transaction tx = session.beginTransaction();

	 	   //创建教师对象
	 	   Teachers t1 = new Teachers("0001","张老师");
	 	   Teachers t2 = new Teachers("0002","黄老师");
	 	   Teachers t3 = new Teachers("0003","李老师");
	 	   Teachers t4 = new Teachers("0004","王老师");

	 	   Students s1 = new Students("张三","男",new Date(),"计算机");
	 	   Students s2 = new Students("李四","男",new Date(),"计算机");
	 	   Students s3 = new Students("王五","女",new Date(),"通信");
	 	   Students s4 = new Students("赵六","女",new Date(),"通信");

	 	   Set<Teachers> set1 = new HashSet<Teachers>();
	 	   set1.add(t1);
	 	   set1.add(t2);

	 	   Set<Teachers> set2 = new HashSet<Teachers>();
	 	   set2.add(t3);
	 	   set2.add(t4);

	 	   Set<Teachers> set3 = new HashSet<Teachers>();
	 	   set3.add(t1);
	 	   set3.add(t3);
	 	   set3.add(t4);

	 	   Set<Teachers> set4 = new HashSet<Teachers>();
	 	   set4.add(t2);
	 	   set4.add(t3);
	 	   set4.add(t4);

	 	   s1.setTeachers(set1);
	 	   s2.setTeachers(set2);
	 	   s3.setTeachers(set3);
	 	   s4.setTeachers(set4);

	 	   session.save(t1);
	 	   session.save(t2);
	 	   session.save(t3);
	 	   session.save(t4);

	 	   session.save(s1);
	 	   session.save(s2);
	 	   session.save(s3);
	 	   session.save(s4);

	 	   tx.commit();
	}
}

这里列举了几个简单的例子,大神直接略过啊~~~~

时间: 2024-12-20 21:48:54

映射关系级别注解的相关文章

Hibernate关系级别注解

最近在学习Hibernate的相关知识,这一站学习的是Hibernate的注解相关的操作和知识.在这里标注以下为以后查阅和需要帮助的朋友提供便利. 一. 开发环境的搭建: 1. 需要的jar包配置: 解释: 这里有连接mysql数据库的包,单体测试包,还有Hibernate的jar包. 二.Hibbernate.cfg.xml配置文件: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hiberna

《Java从入门到放弃》入门篇:使用注解的方式配置hibernate映射关系

之前我们都是使用配置文件的方式来生成的代码,虽然和JDBC比较简单了很多,但每次都在修改时需要既改实体类又改映射文件.还是有点麻烦. 所以,这一篇,我们来说说使用注解的方式来在接在实体类上配置映射关系. 第一步:新建一个项目,或者把之前项目中的实体类.映射文件,还有hibernate中的mapping标签都删除,然后在DBBrowser中再次生成实体类.如下图: 红框中的选项就表示直接在POJO上以注解的方式加上映射关系.注意括号内的hibernate版本,必须是3.2及以上的才行. 生成后的实

Hibernate @Temporal 注解处理Java与Mysql时间日期类型的映射关系

2017-4-2 在 Java 中使用 java.util.Date 和 java.util.Calendar 表示时间.日期类型.在 Mysql 中使用 YEAR.DATE.TIME.TIMESTAMP.DATETIME 五种数据类型表示时间日期,由此引出了 Java 日期类型跟数据库的日期类型怎么映射的问题.本文总结了使用 Hibernate @Temporal 注解的解决方案. 使用 @Temporal 注解修饰 Java 实体类的数据类型 指定 @Temporal value 属性,其中

hibernate注解方式来处理映射关系

在hibernate中,通常配置对象关系映射关系有两种,一种是基于xml的方式,另一种是基于annotation的注解方式,熟话说,萝卜青菜,可有所爱,每个人都有自己喜欢的配置方式,我在试了这两种方式以后,发现使用annotation的方式可以更简介,所以这里就简单记录下通过annotation来配置各种映射关系,在hibernate4以后已经将annotation的jar包集成进来了,如果使用hibernate3的版本就需要引入annotation的jar包. 一.单对象操作 @Entity

hibernate笔记--使用注解(annotation)方式配置单(双)向多对一的映射关系

前面几篇都是介绍的用配置文件来实现实体类到数据库表的映射,这种方式是比较麻烦的,每一个pojo类都需要写一个相应的*.hbm.xml,无疑增加了很多代码量,不过也有优点就是利于维护,为了方便开发,Hibernate还提供了注解方式配置映射文件,非常灵活,减少了配置文件的冗余,虽然维护起来相对比较麻烦,但是的确很方便开发.现在开发中(据说)也越来越流行使用注解,这里贴一个使用注解开发的小例子. 假设有两张表,一张书籍表Book,一张书籍分类表Category,很明显Book和Category是多对

hibernate annotation注解方式来处理映射关系

在hibernate中,通常配置对象关系映射关系有两种,一种是基于xml的方式,另一种是基于annotation的注解方式,熟话说,萝卜青菜,可有所爱,每个人都有自己喜欢的配置方式,我在试了这两种方式以后,发现使用annotation的方式可以更简介,所以这里就简单记录下通过annotation来配置各种映射关系,在hibernate4以后已经将annotation的jar包集成进来了,如果使用hibernate3的版本就需要引入annotation的jar包. 一.单对象操作 @Entity

Hibernate基于注解的双向one-to-many映射关系的实现

在项目中用到了一对多的实体类关系映射,之前接触的都是基于配置文件的映射实现.可是公司的大部分都是基于注解的.因此自己參考之前的代码捣鼓了基于注解的一对多的映射关系实现. 背景: 一的一端:QingAoCenterInfo:青奥场所信息. 多的一端:QingAoPlaceInfo:青奥场馆信息, 当中一个青奥场所下能够包括多个青奥场馆 one端:QingAoCenterInfo,持有QingAoPlaceInfo的List引用, 通过注解@OneToMany(mappedBy="qingAoCen

地图比例尺与高德地图中的缩放级别(0-20)的映射关系与转换方法

一.概述 近期基于高德地图进行了不少开发工作,期间遇到了一个与比例尺相关的问题. 如何将地图比例尺与高德地图中的缩放级别(0-20)对应起来? 二.映射关系 [高德地图api比例尺][https://www.cnblogs.com/yesyes/p/6785705.html] 三.转换方法 高德地图中的zoom是一个float类型的参数,取值范围为(0-20),此处没有做到精细化转换,待后续更新! /** * "scale-zoom"映射关系:https://www.cnblogs.c

hibernate 注解方式讲解映射关系

注解方式讲解映射关系 1       One-To-One Unidirectional with Foreign Key 单向关联外键方式. 1.1         关系如下 学生和地址关系的例子.一个学生住在一个地址上.一个地址只能由一个学生占用. 1.2         Address代码: package com.daodaofun.domain; import javax.persistence.*; @Entity @Table(name="STUDENT") public