Set设置配置

创建数据表:表关系的员工有多重身份

create table EMPLOYEE ( id INT NOT NULL auto_increment, first_name VARCHAR(20) default NULL, last_name VARCHAR(20) default NULL, salary INT default NULL, PRIMARY KEY (id) );
create table CERTIFICATE ( id INT NOT NULL auto_increment, certificate_name VARCHAR(30) default NULL, employee_id INT default NULL, PRIMARY KEY (id) );

创建相应的实体:

package com.study01;

import java.util.Set;

public class Employee {
private int id;
private String firstName;
private String lastName;
private int salary;
private Set certificates; public Employee() {
} public Employee(String fname, String lname, int salary) {
this.firstName = fname;
this.lastName = lname;
this.salary = salary;
} public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} public String getFirstName() {
return firstName;
} public void setFirstName(String firstName) {
this.firstName = firstName;
} public String getLastName() {
return lastName;
} public void setLastName(String lastName) {
this.lastName = lastName;
} public int getSalary() {
return salary;
} public void setSalary(int salary) {
this.salary = salary;
} public Set getCertificates() {
return certificates;
} public void setCertificates(Set certificates) {
this.certificates = certificates;
} }
package com.study01;

public class Certificate {
private int id;
private String name; public Certificate() {
} public Certificate(String name) {
this.name = name;
} public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public boolean equals(Object obj) {
if (obj == null)
return false;
if (!this.getClass().equals(obj.getClass()))
return false;
Certificate obj2 = (Certificate) obj;
//if ((this.id == obj2.getId()) && (this.name.equals(obj2.getName()))) {
// return true;
//}
if(this.name.equals(obj2.getName())) return true;
return false;
} public int hashCode() {
int tmp = 0;
tmp = (id + name).hashCode();
return tmp;
}
}

注意这里对equals和hashCode方法进行了重写。set集合中元素不反复。是否反复。是通过hashCode和equals方法进行比較的。

hibernate主配置文件的配置例如以下:

<?

xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-configuration SYSTEM "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> <!-- Assume test is the database name -->
<property name="hibernate.connection.url"> jdbc:mysql://localhost/test </property>
<property name="hibernate.connection.username"> root </property>
<property name="hibernate.connection.password"> 253503125 </property> <!-- List of XML mapping files -->
<mapping resource="com/study01/Employee.hbm.xml" />
<mapping resource="com/study01/Certificate.hbm.xml" />
</session-factory>
</hibernate-configuration>

映射文件的配置:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.study01">
<class name="Employee" table="EMPLOYEE">
<meta attribute="class-description"> This class contains the employee detail. </meta>
<id name="id" type="int" column="id">
<generator class="native" />
</id>
<set name="certificates" cascade="all">
<key column="employee_id" />
<one-to-many class="Certificate" />
</set>
<property name="firstName" column="first_name" type="string" />
<property name="lastName" column="last_name" type="string" />
<property name="salary" column="salary" type="int" />
</class> </hibernate-mapping>
<?xml version="1.0" encoding="UTF-8"?

>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.study01"> <class name="Certificate" table="CERTIFICATE">
<meta attribute="class-description"> This class contains the certificate records. </meta>
<id name="id" type="int" column="id">
<generator class="native" />
</id>
<property name="name" column="certificate_name" type="string" />
</class>
</hibernate-mapping>

測试:

package com.study01;

import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set; import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration; public class ManageEmployee {
private static SessionFactory factory; public static void main(String[] args) {
try {
factory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
ManageEmployee ME = new ManageEmployee();
HashSet set1 = new HashSet();
set1.add(new Certificate("MCA"));
set1.add(new Certificate("MBA"));
set1.add(new Certificate("PMP"));
set1.add(new Certificate("MCA")); /* Add employee records in the database */
Integer empID1 = ME.addEmployee("Manoj", "Kumar", 4000, set1); HashSet set2 = new HashSet();
set2.add(new Certificate("BCA"));
set2.add(new Certificate("BA"));
Integer empID2 = ME.addEmployee("Dilip", "Kumar", 3000, set2); ME.listEmployees();
/* Update employee's salary records */
ME.updateEmployee(empID1, 5000); /* Delete an employee from the database */
ME.deleteEmployee(empID2); /* List down all the employees */
System.out.println("======================");
ME.listEmployees();
} /* Method to add an employee record in the database */ public Integer addEmployee(String fname, String lname, int salary, Set cert) {
Session session = factory.openSession();
Transaction tx = null;
Integer employeeID = null;
try {
tx = session.beginTransaction();
Employee employee = new Employee(fname, lname, salary);
employee.setCertificates(cert);
employeeID = (Integer) session.save(employee);
tx.commit();
} catch (HibernateException e) {
if (tx != null)
tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
return employeeID;
} /* Method to list all the employees detail */ public void listEmployees() {
Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
List employees = session.createQuery("FROM Employee").list();
for (Iterator iterator1 = employees.iterator(); iterator1.hasNext();) {
Employee employee = (Employee) iterator1.next();
System.out.print("First Name: " + employee.getFirstName());
System.out.print(" Last Name: " + employee.getLastName());
System.out.println(" Salary: " + employee.getSalary());
Set certificates = employee.getCertificates();
for (Iterator iterator2 = certificates.iterator(); iterator2
.hasNext();) {
Certificate certName = (Certificate) iterator2.next();
System.out.println("Certificate: " + certName.getName());
}
}
tx.commit();
} catch (HibernateException e) {
if (tx != null)
tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
} /* Method to update salary for an employee */ public void updateEmployee(Integer EmployeeID, int salary) {
Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Employee employee = (Employee) session.get(Employee.class,
EmployeeID);
employee.setSalary(salary);
session.update(employee);
tx.commit();
} catch (HibernateException e) { if (tx != null)
tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
} /* Method to delete an employee from the records */ public void deleteEmployee(Integer EmployeeID) {
Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Employee employee = (Employee) session.get(Employee.class,
EmployeeID);
session.delete(employee);
tx.commit();
} catch (HibernateException e) {
if (tx != null)
tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
}

注意在Certificate中加入了两个MCA。执行结果例如以下:

First Name: Manoj Last Name: Kumar Salary: 4000
Certificate: PMP
Certificate: MCA
Certificate: MBA
First Name: Dilip Last Name: Kumar Salary: 3000
Certificate: BCA
Certificate: BA
======================
First Name: Manoj Last Name: Kumar Salary: 5000
Certificate: PMP
Certificate: MCA
Certificate: MBA

MCA仅仅出现了一次!注意Certificate中hashCode和equals任务。

版权声明:本文博主原创文章,博客,未经同意不得转载。

hibernate得知——Set设置配置的更多相关文章

  1. atitit.atitit.hb many2one relate hibernate 多对一关联配置..

    atitit.atitit.hb many2one relate hibernate 多对一关联配置.. 1. 多对一单向 @ManyToOne 1 1. 其中@JoinColumn 注解 2 2.  ...

  2. 在 JPA、Hibernate 和 Spring 中配置 Ehcache 缓存

    jpa, hibernate 和 spring 时配置 ehcache 二级缓存的步骤. 缓存配置 首先在 persistence.xml 配置文件中添加下面内容: <property name ...

  3. ssh整合hibernate 使用spring管理hibernate二级缓存,配置hibernate4.0以上二级缓存

    ssh整合hibernate 使用spring管理hibernate二级缓存,配置hibernate4.0以上二级缓存 hibernate  : Hibernate是一个持久层框架,经常访问物理数据库 ...

  4. springmvc+spring-data-jpa+hibernate环境搭建与配置

    1.JPA诞生的缘由是为了整合第三方ORM框架,建立一种标准的方式,百度百科说是JDK为了实现ORM的天下归一,目前也是在按照这个方向发展,但是还没能完全实现.在ORM框架中,Hibernate是一支 ...

  5. PHPSTORM/IntelliJ IDEA 常用 设置配置优化

    PHPSTORM/IntelliJ IDEA 常用 设置配置优化 - meetrice 时间 2014-09-06 10:17:00  博客园-所有随笔区 原文  http://www.cnblogs ...

  6. linux中Zabbix邮件报警设置配置步骤

    使用外部邮箱账号发送报警邮件设置 配置Zabbix服务端外部邮箱 vi /etc/mail.rc #编辑,添加以下信息 set from=xxx@163.com smtp=smtp.163.com s ...

  7. hibernate学习——Set集合配置

    Set集合的配置 数据表的创建:表关系一个员工拥有多个身份 create table EMPLOYEE ( id INT NOT NULL auto_increment, first_name VAR ...

  8. PyCharm 2017 官网 下载 安装 设置 配置 (主题 字体 字号) 使用 入门 教程

    一.安装 Python 3.6 首先,要安装好 Python 3.6.如果你还没有安装,可以参考咪博士之前的教程 Python 3.6.3 官网 下载 安装 测试 入门教程 (windows) 二.官 ...

  9. springmvc 项目完整示例07 设置配置整合springmvc springmvc所需jar包springmvc web.xml文件配置

    前面主要是后台代码,spring以及mybatis的整合 下面主要是springmvc用来处理请求转发,展现层的处理 之前所有做到的,完成了后台,业务层和持久层的开发完成了 接下来就是展现层了 有很多 ...

随机推荐

  1. [置顶] 用mootools实现checkbox全选功能

    全选时,所有的单个checkbox都要选中,反过来也可以实现 //全选按钮 $('chkall').addEvent('click',function(){ $$('input[name=" ...

  2. WebService 之 WSDL文件 解说

    恩,我想说的是,是不是常常有人在开发的时候,特别是和第三方有接口的时候,走的是SOAP协议,然后用户给你一个WSDL文件,说依照上面的进行适配,嘿嘿,这个时候,要是你曾经没有开发过,肯定会傻眼,那假设 ...

  3. WPF的消息机制

    前言 谈起“消息机制”这个词,我们都会想到Windows的消息机制,系统将键盘鼠标的行为包装成一个Windows Message,然后系统主动将这些Windows Message派发给特定的窗口,实际 ...

  4. c#1所搭建的核心基础之值类型和引用类型

    这个主题很重要,在.NET中做的一切其实都是在和一个值类型或者引用类型打交道. 现实世界中的值和引用 假定你在读一份非常棒的东西,希望一个朋友也去读他.于是你到复印室里复印了一份.这个时候他获得了属于 ...

  5. Get RSA public key ASN.1 encode from a certificate in DER format

    RSA public key ASN.1 encode is defined in PKCS#1 as follows: RSAPublicKey :: = SEQUENCE  {     modul ...

  6. Highcharts将数据以图表的形式展现

    1.首先将Highcharts插件所需的js跟css样式文件引入项目中,下载地址为:Highcharts.rar 2.在前台页面中添加一个存放图表的容器 <div id="contai ...

  7. Android架构分析之使用自定义硬件抽象层(HAL)模块

    作者:刘昊昱 博客:http://blog.csdn.net/liuhaoyutz Android版本:2.3.7_r1 Linux内核版本:android-goldfish-2.6.29 在上一篇博 ...

  8. Delphi透明组件开发(去掉自己的csOpaque,去掉父控件的WS_CLIPCHILDREN,增加WS_EX_TRANSPARENT,截获WM_ERASEBKGND,然后在WM_DRAWITEM里画) good

    透明的控件, 一般继承自TGraphicControl的(就是那些没有handle属性, 不能有focus的控件, 如image)都有Transparent属性. 对TWinControl类的控件, ...

  9. QT插件开发方式(没看懂)

    创建一个QT的库项目,删除自动生成的.h和.cpp文件,添加一个接口定义.h文件和一个接口实现类(一个.h一个.cpp).代码如下: 1.接口文件源码 #ifndef PLUGININTERFACE_ ...

  10. 详谈隐藏Tabbar的几种方法

    如今正在写的一个项目,涉及到了使用两个TabBar,然后我须要显示当中一个的时候,然后隐藏另外一个,可是中间却出现故障了.我查了一些资料,想总结一下关于TabBar的隐藏. 第一种方法是: //隐藏t ...