hibernate base
第一个类: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的更多相关文章
- java笔记整理
Java 笔记整理 包含内容 Unix Java 基础, 数据库(Oracle jdbc Hibernate pl/sql), web, JSP, Struts, Ajax Spring, E ...
- HIbernate java.lang.AbstractMethodError: com.microsoft.jdbc.base.BaseDatabaseMetaData.supportsGetGeneratedKeys()Z
[HIbernate]java.lang.AbstractMethodError: com.microsoft.jdbc.base.BaseDatabaseMetaData.supportsGetGe ...
- 报错: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());
- Hibernate全套增删改查+分页
1.创建一个web工程 2.导入jar包 3.创建Student表 4.创建实体类 package com.entity; public class Student { private Integer ...
- 搭建SpringMVC+Spring+Hibernate平台
一. 开发环境 1. 点击此查看并下载需要的 Eclipse IDE for Java EE Developers 开发工具,推荐选用32位 2. 点击此查看并下载需要的 MySQL Server ...
- 【Java EE 学习 69 下】【数据采集系统第一天】【实体类分析和Base类书写】
之前SSH框架已经搭建完毕,现在进行实体类的分析和Base类的书写.Base类是抽象类,专门用于继承. 一.实体类关系分析 既然是数据采集系统,首先调查实体(Survey)是一定要有的,一个调查有多个 ...
- Hibernate 小阶段总结
(一)Hibernate入门 通俗的话来说:Hibernate是用于面向对象操控数据库,对JDBC进行轻量级封装.(在java世界中传统的来说是JDBC访问数据库.) 1)Hibernate定性:对象 ...
- hibernate基础dao类
此文章是基于 搭建SpringMVC+Spring+Hibernate平台 功能:数据库的保存.更新.删除:sql.hql查询:分页查询:调用存储过程 创建hibernate基础dao类: BaseD ...
- Hibernate 简介
其实Hibernate本身是个独立的框架,它不需要任何web server或application server的支持.然而,大多数的Hibernate入门介绍都加入了很多非Hibernate的东西, ...
随机推荐
- C#的is和as操作符来进行强制类型转换&&值类型的拆箱、装箱
if(o is Employee) { Employee e=(Employee)o; //在if语句剩余的部分中使用e; } Employee e=o as Employee; if(e!=null ...
- javascript中apply、call和bind的区别,容量理解,值得转!
a) javascript中apply.call和bind的区别:http://www.cnblogs.com/cosiray/p/4512969.html b) 深入浅出 妙用Javascrip ...
- [猜数字]把两个数和告诉A,积告诉B,求这两个数是什么
1-20的两个数把和告诉A,积告诉B,A说不知道是多少,B也说不知道,这时A说我知道了,B接着说我也知道了,问这两个数是多少? 分析: 设和为S,积为M. 首先,A:我不知道. 说明:S可以分解成多个 ...
- c++ macro
C++ Code 12345678910111213141516171819202122232425262728293031 /* version: 1.0 author: hellogise ...
- Light OJ 1068
数位DP #include <cstdio> #include <cstring> using namespace std; ; ; long long n; int f[MA ...
- ABAP 内表的行列转换
http://www.cnblogs.com/qlp1982/p/3370591.html
- js事件监听器用法实例详解
这篇文章主要介绍了js事件监听器用法,以实例形式较为详细的分析了javascript事件监听器使用注意事项与相关技巧,需要的朋友可以参考下本文实例讲述了js事件监听器用法.分享给大家供大家参考.具体分 ...
- Zookeeper WINDOWS 安装配置
下载:zookeeper:http://mirrors.hust.edu.cn/apache/zookeeper/zookeeper-3.4.6/zookeeper-3.4.6.tar.gz 解压zo ...
- 利用冒泡对List排序
SysMenu是List集合中的类型,在这是一个菜单实体. public List<SysMenu> selfMenuSort(List<SysMenu> list) { fo ...
- Quartz 使用
public class IndexJob:IJob//此处必须实现 IJob接口 { /// <summary> /// 具体的任务 /// </summary> /// & ...