Hibernate学习之单向多对一映射

© 版权声明:本文为博主原创文章,转载请注明出处

说明:该实例是通过映射文件注解两种方式实现的。可根据自己的需要选择合适的方式

实例:

1.项目结构

2.pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  
  	<modelVersion>4.0.0</modelVersion>

	<groupId>org.hibernate</groupId>
	<artifactId>Hibernate-ManyToOne</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<!-- Junit -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>
		<!-- hibernate -->
		<dependency>
		    <groupId>org.hibernate</groupId>
		    <artifactId>hibernate-core</artifactId>
		    <version>5.1.7.Final</version>
		</dependency>
		<!-- MySQL -->
		<dependency>
		    <groupId>mysql</groupId>
		    <artifactId>mysql-connector-java</artifactId>
		    <version>5.1.42</version>
		</dependency>
	</dependencies>
</project>

3.Grade.java

package org.hibernate.entity;

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

import org.hibernate.annotations.GenericGenerator;

@Entity
public class Grade {

	@Id
	@GeneratedValue(generator="gid")
	@GenericGenerator(name="gid", strategy="native")
	private int gid;// 班号
	@Column(length=100)
	private String gname;// 班名
	private String gdesc;// 描述
	
	public Grade() {

	}

	public Grade(String gname, String gdesc) {
		super();
		this.gname = gname;
		this.gdesc = gdesc;
	}

	public int getGid() {
		return gid;
	}
	
	public void setGid(int gid) {
		this.gid = gid;
	}
	
	public String getGname() {
		return gname;
	}
	
	public void setGname(String gname) {
		this.gname = gname;
	}
	
	public String getGdesc() {
		return gdesc;
	}
	
	public void setGdesc(String gdesc) {
		this.gdesc = gdesc;
	}
	
}

4.Student.java

package org.hibernate.entity;

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.Cascade;
import org.hibernate.annotations.GenericGenerator;

@Entity
public class Student {

	@Id
	@GeneratedValue(generator="sid")
	@GenericGenerator(name="sid", strategy="native")
	private int sid;// 学号
	@Column(length=100)
	private String sname;// 姓名
	@Column(length=2)
	private String sex;// 性别
	@ManyToOne(fetch=FetchType.EAGER)
	@Cascade(value=org.hibernate.annotations.CascadeType.SAVE_UPDATE)
	@JoinColumn(name="gid")
	private Grade grade;// 所属班级 
	
	public Student() {
		
	}

	public Student(String sname, String sex, Grade grade) {
		this.sname = sname;
		this.sex = sex;
		this.grade = grade;
	}

	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 getSex() {
		return sex;
	}
	
	public void setSex(String sex) {
		this.sex = sex;
	}

	public Grade getGrade() {
		return grade;
	}

	public void setGrade(Grade grade) {
		this.grade = grade;
	}
	
}

5.Grade.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>

	<class name="org.hibernate.entity.Grade" table="grade">
		<id name="gid" type="java.lang.Integer">
			<column name="gid"/>
			<generator class="native"/>
		</id>
		<property name="gname" type="java.lang.String">
			<column name="gname" length="100"></column>
		</property>
		<property name="gdesc" type="java.lang.String">
			<column name="gdesc"/>
		</property>
	</class>

</hibernate-mapping>

6.Student.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>

	<class name="org.hibernate.entity.Student" table="student">
		<id name="sid" type="java.lang.Integer">
			<column name="sid"/>
			<generator class="native"/>
		</id>
		<property name="sname" type="java.lang.String">
			<column name="sname" length="100"/>
		</property>
		<property name="sex" type="java.lang.String">
			<column name="sex" length="2"/>
		</property>
		<!-- 配置单向的多对一关联关系 -->
		<many-to-one name="grade" cascade="save-update" column="gid" class="org.hibernate.entity.Grade"/>
	</class>

</hibernate-mapping>

7.hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
	"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
	"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>

	<!-- 配置SessionFactory -->
	<session-factory>
		<!-- 配置数据库连接信息 -->
		<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="connection.url">
			jdbc:mysql:///hibernate?useSSL=true&amp;characterEncoding=UTF-8
		</property>
		<property name="connection.username">root</property>
		<property name="connection.password">***</property>
		<!-- 配置hibernate常用属性 -->
		<property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property><!-- 方言 -->
		<property name="hbm2ddl.auto">update</property><!-- 是否自动创建表结构 -->
		<property name="show_sql">true</property><!-- 是否显示SQL -->
		<!-- 引入映射类 -->
		<!-- <mapping class="org.hibernate.entity.Student"/>
		<mapping class="org.hibernate.entity.Grade"/> -->
		<!-- 引入映射文件 -->
		<mapping resource="hbm/Student.hbm.xml"/>
		<mapping resource="hbm/Grade.hbm.xml"/>
	</session-factory>

</hibernate-configuration>

8.TestManyToOne.java

package org.hibernate.test;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.entity.Grade;
import org.hibernate.entity.Student;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class TestManyToOne {

	private SessionFactory sessionFactory;
	private Session session;
	private Transaction transaction;
	
	@Before
	public void before() {
		
		// 创建SessionFactory对象
		sessionFactory = new Configuration().configure().buildSessionFactory();
		// 获取Session对象
		session = sessionFactory.openSession();
		// 开启事务
		transaction = session.beginTransaction();
		
	}
	
	@After
	public void after() {
		
		// 提交事务
		transaction.commit();
		// 关闭Session
		session.close();
		// 关闭SessionFactory
		sessionFactory.close();
		
	}
	
	@Test
	public void testAdd() {
		
		Grade grade = new Grade("Java一班", "Java应用开发一班");
		Student student1 = new Student("张三", "男", grade);
		Student student2 = new Student("李四", "男", grade);
		
		session.save(grade);
		session.save(student1);
		session.save(student2);
		
	}
	
	@Test
	public void testQuery() {
		
		Student student = session.get(Student.class, 1);
		System.out.println(student.getSname() + " - " + student.getSex() + " - "
				+ student.getGrade().getGname() + " - " + student.getGrade().getGdesc());
		
	}
	
	@Test
	public void testUpdate() {
		
		Grade grade = new Grade("Java二班", "Java应用开发二班");
		Student student = session.get(Student.class, 2);
		student.setGrade(grade);
		
		session.update(student);
		
	}
	
	@Test
	public void testDelete() {
		
		Student student = session.get(Student.class, 2);
		session.delete(student);
		
	}
	
}

9.效果预览

  9.1 执行testAdd方法

  9.2 执行testQuery方法

  9.3 执行testUpdate方法

  9.4 执行testDelete方法

 

参考:http://www.imooc.com/video/8675

        http://www.imooc.com/video/10089

posted @ 2017-06-13 14:24  禁忌夜色153  阅读(252)  评论(0编辑  收藏  举报