单边一对多关系:电子邮件管理

单边一对多关系:指一方有集合属性,包含多个多方,而多的一方没有一方的引用。

比如:用户(一)与电子邮件(多)。一个用户可以有多个电子邮件记录。

目的:通过OneToMany映射,当保存用户信息到用户表tb_person时,也能自动保存该用户的邮件的信息到邮件表tb_email

   当删除用户信息时,也自动从数据库删除该用户的邮件的信息

实现效果:

用户:     邮件表:

工程目录:(这里用java EE 6 Libraries,5会报错)

jar包

Hibernate的注解方式可以自动生成数据表,不需要自己建表,只需在xml配置文件设置hbm2ddl.auto为create

代码如下:

1、Person.java(用户实体类)

package com.hibernate.bean;

import java.util.ArrayList;
import java.util.List; import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table; @Entity
@Table(name="tb_person")
public class Person { @Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer id; private String name;
//一对多配置,并配置列关系
@OneToMany(fetch=FetchType.LAZY,targetEntity=Email.class,
cascade={CascadeType.PERSIST,CascadeType.REMOVE,CascadeType.MERGE,CascadeType.REFRESH})
//指定连接表Email中的person_id外键列,参照当前实体对应表的主键列id
@JoinColumns(value = { @JoinColumn(name="person_id",referencedColumnName="id") })
//配置排序方法
@OrderBy(value="email desc")
private List<Email> emails=new ArrayList<Email>(); //用户方有邮件方的集合属性,包含多个多方,用泛型<Email>指定Email对象 public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public List<Email> getEmails() {
return emails;
} public void setEmails(List<Email> emails) {
this.emails = emails;
} }

Person实体类中使用@OneToMany配置一对多关系。fetch配置加载方式(延迟加载FetchType.LAZY或即时加载FetchType.EAGER)。

targetEntity中配置集合属性中的类型, 由于emails属性类型为List<Email>,用泛型指定了集合内为Email对象,因此targetEntity可省略。

cascade配置级联方式,本例配置为PERSIST、REMOVE、MERGE、REFRESH,表示在保存、删除、修改、刷新Person类时,可以通过操作Person类来操作Email类。CascadeType.ALL表示所有类型

2、Email.java(邮件实体类)

package com.hibernate.bean;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table; @Entity
@Table(name="tb_email")
public class Email { @Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer id; private String email; public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getEmail() {
return email;
} public void setEmail(String email) {
this.email = email;
} }

3、HibernateSessionFactory.java

package com.hibernate.bean;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration; /**
* Configures and provides access to Hibernate sessions, tied to the current
* thread of execution. Follows the Thread Local Session pattern, see
* {@link http://hibernate.org/42.html }.
*/
public class HibernateSessionFactory { /**
* Location of hibernate.cfg.xml file. Location should be on the classpath
* as Hibernate uses #resourceAsStream style lookup for its configuration
* file. The default classpath location of the hibernate config file is in
* the default package. Use #setConfigFile() to update the location of the
* configuration file for the current session.
*/
private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static Configuration configuration = new AnnotationConfiguration();
private static org.hibernate.SessionFactory sessionFactory;
private static String configFile = CONFIG_FILE_LOCATION; static {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
} private HibernateSessionFactory() {
} /**
* Returns the ThreadLocal Session instance. Lazy initialize the
* <code>SessionFactory</code> if needed.
*
* @return Session
* @throws HibernateException
*/
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get(); if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
} return session;
} /**
* Rebuild hibernate session factory
*
*/
public static void rebuildSessionFactory() {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
} /**
* Close the single hibernate session instance.
*
* @throws HibernateException
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null); if (session != null) {
session.close();
}
} /**
* return session factory
*
*/
public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
} /**
* return session factory
*
* session factory will be rebuilded in the next call
*/
public static void setConfigFile(String configFile) {
HibernateSessionFactory.configFile = configFile;
sessionFactory = null;
} /**
* return hibernate configuration
*
*/
public static Configuration getConfiguration() {
return configuration;
} }

4、hibernate.cfg.xml(src目录下)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="connection.url">jdbc:oracle:thin:@192.168.1.2::orcl</property>
<property name="connection.username">daym2</property>
<property name="connection.password">daym2</property>
<property name="connection.isolation"></property>
<property name="hbm2ddl.auto">create</property>
<property name="javax.persistence.validation.mode">none</property> <!-- SQL方言,这边设定的是Oracle -->
<property name="dialect">org.hibernate.dialect.Oracle10gDialect</property> <property name="current_session_context">thread</property>
<mapping class="com.hibernate.bean.Cat" />
<mapping class="com.hibernate.bean.Person" />
<mapping class="com.hibernate.bean.Email" />
</session-factory>
</hibernate-configuration>

5、TestPersonEmail.java测试类

package com.hibernate.bean;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction; public class TestPersonEmail { public static void main(String[] args) {
Person person=new Person();
person.setName("Jane"); Email email=new Email(); //实例化一个Email
email.setEmail("yahoo@yahoo.com.cn");//设置Email
person.getEmails().add(email); //添加到Person对象中 email=new Email(); //实例化另一个Email
email.setEmail("163@163.com");//设置Email
person.getEmails().add(email);//添加到Person对象中 Session session=HibernateSessionFactory.getSession();
//开启一个事务
session.beginTransaction();
session.persist(person);//保存person对象,会自动级联保存Email对象 List list=session.createQuery("select p from Person p left join fetch p.emails e where e.email like '%@yahoo.com.cn' ").list();
for(Person p: (List<Person>)list){
System.out.println("Person:"+p.getName());
for(Email e:p.getEmails()){
System.out.println("\tEmail:"+e.getEmail());
}
}
//session.delete(person);//删除person对象,会自动级联删除属于它的Email记录 session.getTransaction().commit();
session.close();
}
}

6、log4j.properties(src目录下)

log4j.rootLogger=INFO,stdout
log4j.category.org.hibernate.tool.hbn2ddl=DEBUG
log4j.category.org.hibernate.SQL=DEBUG
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%-d{yyyy-MM-dd HH\:mm\:ss,SSS} [%c]-[%p] %m%n

Hibernate实体关系映射(OneToMany单边)——完整实例的更多相关文章

  1. Hibernate实体关系映射(OneToMany、ManyToOne双边)——完整实例

    双边关系是最常见的配置.在多方有一方的引用,一方也有多方的引用.双边关系能够很方便地查询数据.看一个班级与学生的双边关系. 班级(Clazz类)与学生(Student类):一对多关系.班级中有学生属性 ...

  2. hibernate 实体关系映射笔记

    @经常使用属性说明:     @Entity:实体类     @Table:指定相应数据表     @Id:主键,使用能够为null值的类型,假设实体类没有保存到数据库是一个暂时状态     @Col ...

  3. JPA实体关系映射:@ManyToMany多对多关系、@OneToMany@ManyToOne一对多多对一关系和@OneToOne的深度实例解析

    JPA实体关系映射:@ManyToMany多对多关系.@OneToMany@ManyToOne一对多多对一关系和@OneToOne的深度实例解析 今天程序中遇到的错误一 org.hibernate.A ...

  4. JPA总结——实体关系映射(一对多@OneToMany)

    JPA总结——实体关系映射(一对多@OneToMany) 注意:本文出自“阿飞”的博客,如果要转载本文章,请与作者联系! 并注明来源: http://blog.sina.com.cn/s/blog_4 ...

  5. Hibernate注解关系映射

    Hibernate Annotation关系映射的几种类型映射用法及使用方法(说明:以前实例的实体是user和role,主键分别是userid和roleid)   1)一对一外键关联映射(单向) @O ...

  6. hibernate(3) —— 关系映射

    hibernate中关系映射指的是实体类与实体类间的关系.和数据库中表与表之间的关系类似,有一对一,多对一,一对多,多对多四种映射关系. 一:一对一映射 两个对象之间是一对一的关系,如人和身份证之间是 ...

  7. Java IDE 编辑器 --- IntelliJ IDEA 进阶篇 生成 hibernate 实体与映射文件

    原文:转:Java IDE 编辑器 --- IntelliJ IDEA 进阶篇 生成 hibernate 实体与映射文件 2011-04-30 12:50 很多人不知道怎么用 IntelliJ IDE ...

  8. [刘阳Java]_MyBatis_实体关系映射_第8讲

    MyBatis既然是一个ORM框架,则它也有像Hibernate那样的一对多,多对多,多对一的实体关系映射功能.下面我们就来介绍一下如何使用MyBatis的实体关系映射 1.MyBatis实体关系映射 ...

  9. OrchardNoCMS实体关系映射扩展

    在OrchardNoCMS中,默认的系统会把实体关系映射保存到mappings.bin文件中. 如果不进行任何修改,默认的可以自动保存关系映射的model是有很大限制的. 条件是model的命名空间必 ...

随机推荐

  1. ASP.NET中cookie与Fiter实现简单登陆,AllowAnonymous匿名登陆

    向服务器发送cookie 在登陆的时候,我们可以可以通过下列代码,向服务器发送cookie,其中包括自己的账号信息(不涉及加密),用以后面判断访问者. HttpCookie cookie = new ...

  2. C#字节数组转换成字符串

    C#字节数组转换成字符串 如果还想从 System.String 类中找到方法进行字符串和字节数组之间的转换,恐怕你会失望了.为了进行这样的转换,我们不得不借助另一个类:System.Text.Enc ...

  3. 集群节点间网络通信TIPC

    1. TIPC背景介绍 TIPC主要是用于集群网络环境之中,它这个协议有一些前提假设包括: 协议发送的大部分message都是直接到达目的地(无路由): message的传输时间都很短; messag ...

  4. 欧拉回路(hdu3018)

    刚学图论不久,看着别人的博客慢慢学了一点基础的,感觉还是有点力不从心,感觉图论的题好多长得都很像,什么太监算法(Tarjan),Kosaraju,当然最基础的还是并查集...好了继续介绍这道题.... ...

  5. 115开jiang监控

    ぁぁあ0ぁぁあ这里是返回值为1的时候下标2的值ぁぁあ

  6. linux下的nodejs安装

      linux下安装nodejs的方式: 1.源码安装 2.nvm安装 这里推荐使用nvm安装,避免下载nodejs源码:   安装步骤: 一.安装git        一般linux系统的git版本 ...

  7. ubuntu16.04 + ubuntu + apache2 配置apache解析php

    给apache安装php扩展:  sudo apt-get install libapache2-mod-php 注:这是apache解析php文件的关键,光修改配置文件不安装扩展是不起作用的. 目录 ...

  8. Spring-boot-admin功能说明

    http://blog.csdn.net/xingfulangren/article/details/52304413 **************************************** ...

  9. nodejs的第四天学习笔记

    一. ECMAScript6(es2015)es6语法 es6/es2015,在es5的基础上扩展了很多新的功能,我们要学习仅仅是es6中的部分常用新功能,这些功能在使用的时候一定要慎重,因为他们之中 ...

  10. SQL函数之---DECODE函数

    Decode函数是oracle/SQL提供的特有函数计算方式,语法:DECODE(value,if1,then1,if2,then2,if3,then3,...else),通常我们在写语句的时候可能会 ...