第一个类: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