第一个类:Person.java

package org.crazyit.app.domain;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.MapKeyClass;
import javax.persistence.MapKeyColumn;
import javax.persistence.OrderColumn;
import javax.persistence.Table;

@Entity
@Table(name = "person_inf")
public class Person implements Serializable {
/**
*
*/
private static final long serialVersionUID = 7093602310657352229L;

// 标识属性
//@Id
//@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "person_id")
private Integer id;
private int age;
// private String name;

// 组件属性
//private Name name;

// // 多列作为联合主键,对象实现序列号,有无参构造,建议重写equal()和hashCode()方法
// @Id // 属性标识
// private String first;
// @Id // 属性标识
// private String last;

//组件属性,作为复合主键,标识对象属性,并且有程序给出标识属性值。此时person对象的标识属性不再是id.
//组件必须序列号,有无参构造方法,建议重写equal()和hashCode()方法。
@EmbeddedId
// @AttributeOverrides({
// @AttributeOverride(name="first",column=@Column(name="first_Name")),
// @AttributeOverride(name="last",column=@Column(name="last_name"))
// })
private Name name;

/*// 说明:映射组件内集合属性的注解与映射实体类里集合属性的注解没有任何区别。
// map集合属性==组件属性为集合,保存该对象关联的程度(比如:好坏)
@ElementCollection(targetClass = Integer.class)
@CollectionTable(name = "power_inf", // 指定表名
joinColumns = @JoinColumn(name = "person_id", nullable = false) )
@MapKeyColumn(name = "name_aspect")
@MapKeyClass(String.class)
@Column(name = "name_power", nullable = false)
private Map<String, Integer> power = new HashMap<String, Integer>();

// list集合属性元素为组件
@ElementCollection(targetClass = Name.class)
@CollectionTable(name = "nick_power_inf", joinColumns = @JoinColumn(name = "person_id", nullable = false) )
@OrderColumn(name = "list_order")
private List<Name> nicks = new ArrayList<Name>();

// map集合元素的key为组件,则需要重写该组件的equal()和hashCode()方法。
// 建议使用@MapKeyClass注解指定MapKey的类型

// List集合属性性,保存该对象关联的学校
@ElementCollection(targetClass = String.class)
// 映射保存集合属性的表
@CollectionTable(name = "school_inf", // 指定表名
joinColumns = @JoinColumn(name = "person_id", nullable = false) )
// 指定保存集合元素的列为school_name
@Column(name = "school_name")
// 映射集合元素索引的列
@OrderColumn(name = "list_order")
List<String> schools = new ArrayList<String>();

// Set集合属性,保存该对象关联的工作
@ElementCollection(targetClass = String.class)
@CollectionTable(name = "job_inf", // 指定表名
joinColumns = @JoinColumn(name = "person_id", nullable = false) )
// 指定保存元素的列为job_name,nullable=false增加非空约束
@Column(name = "job_name")
Set<String> jobs = new HashSet<String>();
*/
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 int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

/* public List<String> getSchools() {
return schools;
}

public void setSchools(List<String> schools) {
this.schools = schools;
}

public Set<String> getJobs() {
return jobs;
}

public void setJobs(Set<String> jobs) {
this.jobs = jobs;
}

public Name getName() {
return name;
}*/

public void setName(Name name) {
this.name = name;
}

/* public Map<String, Integer> getPower() {
return power;
}

public void setPower(Map<String, Integer> power) {
this.power = power;
}

public List<Name> getNicks() {
return nicks;
}

public void setNicks(List<Name> nicks) {
this.nicks = nicks;
}
*/
/* public String getFirst() {
return first;
}

public void setFirst(String first) {
this.first = first;
}

public String getLast() {
return last;
}

public void setLast(String last) {
this.last = last;
}*/

}

//第二个类:Name.java

package org.crazyit.app.domain;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.persistence.EmbeddedId;
import javax.persistence.Id;

import org.hibernate.annotations.Parent;

/**
* 映射组件
*
* @author user
*
*/
@Embeddable//标识组件
public class Name implements Serializable {

/**
*
*/
private static final long serialVersionUID = 5930988577308921103L;
@Column(name = "first_name")
private String first;
@Column(name = "last_name")
private String last;
@Parent
private Person ower;

// 无参构造方法
public Name() {
}

// 初始化全部成员变量
public Name(String first, String last) {
this.first = first;
this.last = last;
}

// 重写equal和hashCode方法
public String getFirst() {
return first;
}

@Override
public int hashCode() {
final int prime = 31;
return getFirst().hashCode() * prime + getLast().hashCode();
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj != null && obj.getClass() == Name.class) {
Name target = (Name) obj;
return target.getFirst().equals(getFirst()) && target.getLast().equals(getLast());
}
return false;
}

public void setFirst(String first) {
this.first = first;
}

public String getLast() {
return last;
}

public void setLast(String last) {
this.last = last;
}

public Person getOwer() {
return ower;
}

public void setOwer(Person ower) {
this.ower = ower;
}
}

//第三个类:主类Start.java

package org.crazyit.app.service;

import org.crazyit.app.domain.Name;
import org.crazyit.app.domain.Person;
import org.crazyit.app.utils.HibernateSessionFactory;
import org.hibernate.Session;

public class Start {

public static void main(String[] args) {

Session session = HibernateSessionFactory.currentSession();
session.beginTransaction();

// //集合属性实例
// Person person = new Person();
// person.setAge(20);
// person.setName("crazyit.org");
// // list集合属性
// person.getSchools().add("小学");
// person.getSchools().add("中学");
// // set集合属性
// person.getJobs().add("开发");
// person.getJobs().add("测试");
// session.save(person);

// //组件属性实例
// Person person=new Person();
// person.setAge(20);
// //设置组件属性
// person.setName(new Name("liu","xw"));
// session.save(person);

// //组件属性为集合
// Person person=new Person();
// person.setAge(20);
// person.getPower().put("0", 1);
// person.getPower().put("1", 1);
// session.save(person);

// //集合属性的元素为组件
// Person person=new Person();
// person.setAge(20);
// person.getNicks().add(new Name("z","xj"));
// person.getNicks().add(new Name("liu","xj"));
// session.save(person);

//组件作为复合主键=======>bug:运行出错了?
//出错原因,集合属性和集合组件那些知识点的中,@joinColumn定义了外键约束条件,所以会报错。
//注释掉这些,就可以测试这个知识点。
Person person = new Person();
person.setName(new Name("z", "xj"));
person.setName(new Name("liu", "xj"));
session.save(person);

// //多列作为联合主键
// Person person=new Person();
// person.setFirst("liu");
// person.setLast("xiaowei");
// session.save(person);

session.getTransaction().commit();
HibernateSessionFactory.closeSession();
}
}

///////////////////////////////////////////////////////////

项目启动:

1.配置文件: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="connection.url">jdbc:mysql://localhost:3306/db_hibernate</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hbm2ddl.auto">create</property>
<property name="show_sql">true</property>
<!-- c3p0配置 -->
<property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.min_size">1</property>
<property name="hibernate.c3p0.timeout">5000</property>
<property name="hibernate.c3p0.max_statements">100</property>
<property name="hibernate.c3p0.idle_test_period">3000</property>
<property name="hibernate.c3p0.acquire_increment">2</property>
<property name="hibernate.c3p0.validate">true</property>
<!-- 罗列所有持久化类的类名 -->
<mapping class="org.crazyit.app.domain.News"/>
<mapping class="org.crazyit.app.domain.Person"/>
</session-factory>
</hibernate-configuration>

//2.sessionFactory工具类:HibernateSessionFactory.java

package org.crazyit.app.utils;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;

public class HibernateSessionFactory {
/**
* Examples:
* CONFIG_FILE_LOCATION = "/hibernate.conf.xml".
* CONFIG_FILE_LOCATION = "/com/foo/bar/myhiberstuff.conf.xml".
*/
private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
/** Holds a single instance of Session */
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
/** The single instance of hibernate configuration */
private static final Configuration cfg = new Configuration();
/** The single instance of hibernate SessionFactory */
private static org.hibernate.SessionFactory sessionFactory;

/**
* Returns the ThreadLocal Session instance. Lazy initialize the
* SessionFactory if needed.
*
* @return Session
* @throws HibernateException
*/
@SuppressWarnings("deprecation")
public static Session currentSession() throws HibernateException {
Session session = (Session) threadLocal.get();

if (session == null) {
if (sessionFactory == null) {
try {
cfg.configure(CONFIG_FILE_LOCATION);
sessionFactory = cfg.buildSessionFactory();
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
session = sessionFactory.openSession();
threadLocal.set(session);
}

return session;
}
/**
* 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();
}
}
/**
* Default constructor.
*/
private HibernateSessionFactory() {

}
}

//3.引入的jars,测试使用的是hibernate-release-4.3.5.Final

hibernate/lib/required目录下所有jar
hibernate/lib/optional/c3p0目录下所有jar
mysql驱动jar

hibernate base的更多相关文章

  1. java笔记整理

    Java 笔记整理 包含内容     Unix Java 基础, 数据库(Oracle jdbc Hibernate pl/sql), web, JSP, Struts, Ajax Spring, E ...

  2. HIbernate java.lang.AbstractMethodError: com.microsoft.jdbc.base.BaseDatabaseMetaData.supportsGetGeneratedKeys()Z

    [HIbernate]java.lang.AbstractMethodError: com.microsoft.jdbc.base.BaseDatabaseMetaData.supportsGetGe ...

  3. 报错:Caused by: org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save(): cn.itcast.bos.domain.base.SubArea

    因为 实体类中的主键 是String类型 不能自动为其分配id  所以需要手动设置在service层   model.setId(UUID.randomUUID().toString());

  4. Hibernate全套增删改查+分页

    1.创建一个web工程 2.导入jar包 3.创建Student表 4.创建实体类 package com.entity; public class Student { private Integer ...

  5. 搭建SpringMVC+Spring+Hibernate平台

    一. 开发环境 1. 点击此查看并下载需要的 Eclipse IDE for Java EE Developers 开发工具,推荐选用32位   2. 点击此查看并下载需要的 MySQL Server ...

  6. 【Java EE 学习 69 下】【数据采集系统第一天】【实体类分析和Base类书写】

    之前SSH框架已经搭建完毕,现在进行实体类的分析和Base类的书写.Base类是抽象类,专门用于继承. 一.实体类关系分析 既然是数据采集系统,首先调查实体(Survey)是一定要有的,一个调查有多个 ...

  7. Hibernate 小阶段总结

    (一)Hibernate入门 通俗的话来说:Hibernate是用于面向对象操控数据库,对JDBC进行轻量级封装.(在java世界中传统的来说是JDBC访问数据库.) 1)Hibernate定性:对象 ...

  8. hibernate基础dao类

    此文章是基于 搭建SpringMVC+Spring+Hibernate平台 功能:数据库的保存.更新.删除:sql.hql查询:分页查询:调用存储过程 创建hibernate基础dao类: BaseD ...

  9. Hibernate 简介

    其实Hibernate本身是个独立的框架,它不需要任何web server或application server的支持.然而,大多数的Hibernate入门介绍都加入了很多非Hibernate的东西, ...

随机推荐

  1. Git – Fast Forward 和 no fast foward

    Git 很是强大,在体验过rebase的华丽之后,再次发现之前在TFS上遇到的问题一下都有解了.但也印证了Git深入并非易事.这篇就谈下一个容易迷糊的概念:Fast forward. Fast-For ...

  2. 向SqlServer数据库插入数据

    Insert Values Insert Select Insert Exec Select Into Bulk Insert Insert Values是最常用的一种插入数据的方式,基本语法如下,表 ...

  3. 错误描述:请求“System.Data.SqlClient.SqlClientPermission, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089”类型的权限已失败

    错误描述:请求“System.Data.SqlClient.SqlClientPermission, System.Data, Version=2.0.0.0, Culture=neutral, Pu ...

  4. perl q qq qr qw qx 区别与使用方法

    1.q 相当于 单引号' ' 转义字符无效 q可以使用()[] {} // ,, 2.qq 相当于" " 转义字符有效 qq可以使用()[] {} // ,, 3.qw  相当于 ...

  5. zsh 通信脚本

    server #!/bin/zsh #zsh TCP server script zmodload zsh/net/tcp #listening port ztcp -l #This is a fil ...

  6. python2.7之MySQLdb模块 for linux安装

    1.下载:MySQL-pythonhttp://sourceforge.net/projects/mysql-python/files/mysql-python-test/1.2.3b1/MySQL- ...

  7. iOS进阶面试题----Block部分

    1 什么是block 对于闭包 (block),有很多定义,其中闭包就是能够读取其它函数内部变量的函数,这个定义即接近本质又较好理解.对于刚接触Block的同学,会觉得有些绕, 因为我们习惯写这样的程 ...

  8. 关于Windows下的文件后缀名问题

    一.背景说明 有很多的小伙伴对windows下的文件后缀名不能很好地理解作用和区别,更不用说高深的使用了,在这里给大家说一下这些文件后缀名到底有什么区别,有什么作用呢? 二.说明 简单的说来,wind ...

  9. nyoj998(euler)

    题意:题意:给出n和m,求满足条件gcd(x, n)>=m的x的gcd(x, n)的和,其中1<=x<=n,1<= n, m <= 1e9:思路:此题和nyoj1007差 ...

  10. NYOJ题目112指数运算

    aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAs0AAAIICAIAAAAaCETRAAAgAElEQVR4nO3drW7jWtwv4PcmwnMhxb ...