阶段性总结
hibernate开发的三种方式中,
domain.object+映射文件 自动创建对应的数据库
需要手动配置hibernate.cfg.xml
<property name="hbm2ddl.auto>create
有四个配置项 create update create-drop validate
create:
update:
create-drop
validate:
<property name="hbm2ddl.auto">create</property>
HibernateUtil.openSession();加载hibernate.cfg.xml文件就会自动创建,会覆原来已存在的数据
<property name="hbm2ddl.auto">update</property>
如果没表则创建,如果表已存在,则更新,若字段名变更则增加字段而不是覆盖原来的字段
字段类型变化则覆盖。
<property name="hbm2ddl.auto">create-drop</property>
在显示sessionFactory时,把已存在的数据清空。
<property name="hbm2ddl.auto">validate</property>
在开发测试过程中,配置哪个都行,项目发布后不应改动。
domain对象的细节问题。
1.默认的无参构造方法
2.无意义的id标示符
3.属性有get、set方法
4.hibernate更关心的是对象关系映射文件,但domain中不存在属性的话会报错。
hibernate.hbm.xml 有些属性是可选的,若不配置,会采用默认配置。比如表名、属性类型。但建议还是写上。
- 1.初始化代码
Configuration cfg=new Configuration();
cfg.configure().("hibernate.cfg.xml");
SessionFactory sessionFactory=cfg.buildSessioinFactory();
- 2.模板代码
Session session=null;
Transaction tx=null;
try {
session=HibernateUtil.getCurrentSession();
tx=session.beginTransaction();
tx.commit();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
if(tx!=null){
tx.rollback();
}
throw new RuntimeException(e.getMessage());
}finally{
if(session!=null && session.isOpen()){
session.close();
}
}
hibernate对象的三种状态
transient 瞬时态
数据库中没有数据与之对应,超过作用于会被JVM垃圾回收器回收,一般是new出来且与session没有关联的对象。
persistent 持久态
数据库中有数据与之对应,当前与session有关联,且相关联的session没有关闭,事务没有提交,持久对象状态发生改变,在事务提交时会影响到数据库能否被hibernate检测到。
detached 游离态
数据库中有数据与之对应,但当前没有session与之关联;脱管对象状态发生改变,hibernate不能检测到。
如何判断一个对象所处状态。
看session是否处于session,看数据库中是否有对应记录
package com.qq.view;
import com.qq.util.*;
import com.qq.domain.*;
import org.hibernate.Session;
import org.hibernate.Transaction;
import java.util.List;
import java.util.Iterator;
import java.util.Set;
import org.hibernate.Query;
public class TestMain {
private static Session session=null;
private static Transaction ts=null;
public static void main(String[] args){
//hibernate对象的三种状态
Course c1=new Course(); //c1就是transient
c1.setCid(8L);
c1.setCcredit(3L);
c1.setCname("Java程序设计");
Session session=null;
Transaction tx=null;
try {
session=HibernateUtil.getCurrentSession();
tx=session.beginTransaction();
session.save(c1);
System.out.println(c1.getCname()); //c1处于session管理下,同时c1被保存到数据库中,因此处于persistent
tx.commit();//提交后会自动关闭session
//c1被保存到数据库中,但不处于session管理下,处于detached状态
System.out.println(c1.getCname());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
if(tx!=null){
tx.rollback();
new RuntimeException(e.getMessage());
}
}finally{
if(session!=null && session.isOpen()){
session.close();
}
}
}
}
many-to-one 问题
从domain入手,纯粹面向对象,通过hbm.xml建立数据库
<?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">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
<session-factory>
<property name="connection.username">scott</property>
<property name="connection.url">
jdbc:oracle:thin:@127.0.0.1:1521:orcl
</property>
<property name="dialect">
org.hibernate.dialect.Oracle9Dialect
</property>
<property name="connection.password">tiger</property>
<property name="connection.driver_class">
oracle.jdbc.driver.OracleDriver
</property>
<property name="show_sql">true</property>
<!-- 配置 自动创建关系模型 -->
<property name="hbm2ddl.auto">update</property>
<mapping resource="com/qq/domain/Department.hbm.xml" />
<mapping resource="com/qq/domain/Student.hbm.xml" />
</session-factory>
</hibernate-configuration>
package com.qq.domain;
public class Department implements java.io.Serializable{
private static final long serialVersionUID=1L;
private Integer id;
private String name;
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;
}
}
```xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping package="com.qq.domain">
<class name="Department">
<id name="id" type="java.lang.Integer">
<generator class="sequence">
<param name="sequence">dept_seq</param>
</generator>
</id>
<property name="name" type="java.lang.String">
<column name="name" length="64" not-null="true"/>
</property>
</class>
</hibernate-mapping>
package com.qq.domain;
public class Student implements java.io.Serializable{
private static final long serialVersionUID=1L;
private Integer id;
private String name;
private Department dept;
public Department getDept() {
return dept;
}
public void setDept(Department dept) {
this.dept = dept;
}
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;
}
}
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
<class name="Student">
<id name="id" type="java.lang.Integer">
<generator class="sequence">
<param name="sequence">stu_seq</param>
</generator>
</id>
<property name="name" type="java.lang.String">
<column name="name" length="64"/>
</property>
<!-- 对于private Department dept就不能用property来配置了 将来自动生成的外键名dept_id-->
<many-to-one name="dept" column="dept_id"/>
</class>
</hibernate-mapping>
package com.qq.util;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
final public class HibernateUtil {
private static SessionFactory sessionFactory=null;
//使用线程局部模式
private static ThreadLocal<Session> threadLocal=new ThreadLocal<Session>();
private HibernateUtil(){};
static {
sessionFactory=new Configuration().configure().buildSessionFactory();
}
//获取全新的全新的sesession
public static Session openSession(){
return sessionFactory.openSession();
}
//获取和线程关联的session
public static Session getCurrentSession(){
Session session=threadLocal.get();
//判断是否得到
if(session==null){
session=sessionFactory.openSession();
//把session对象设置到 threadLocal,相当于该session已经和线程绑定
threadLocal.set(session);
}
return session;
}
public static void closeCurrentSession(){
Session s=getCurrentSession();
if(s!=null&& s.isOpen() ){
s.close();
threadLocal.set(null);
}
}
//这里提供一个根据id返回对象的方法
public static Object findById(Class clazz,java.io.Serializable id){
Session s=null;
Transaction tx=null;
Object obj=null;
try {
s=openSession();
tx=s.beginTransaction();
obj=s.load(clazz, id);
tx.commit();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
// TODO: handle exception
}finally{
if(s!=null&&s.isOpen()){
s.close();
}
}
return obj;
}
//统一的一个修改和删除(批量 hql) hql"delete upate ...??"
public static void executeUpdate(String hql,String [] parameters){
Session s=null;
Transaction tx=null;
try {
s=openSession();
tx=s.beginTransaction();
Query query=s.createQuery(hql);
//先判断是否有参数要绑定
if(parameters!=null&& parameters.length>0){
for(int i=0;i<parameters.length;i++){
query.setString(i, parameters[i]);
}
}
query.executeUpdate();
tx.commit();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
// TODO: handle exception
}finally{
if(s!=null&&s.isOpen()){
s.close();
}
}
}
//如果要配置openSessionInView
//统一的一个修改和删除(批量 hql) hql"delete upate ...??"
public static void executeUpdateOpenInView(String hql,String [] parameters){
Session s=getCurrentSession();
Query query=s.createQuery(hql);
//先判断是否有参数要绑定
if(parameters!=null&& parameters.length>0){
for(int i=0;i<parameters.length;i++){
query.setString(i, parameters[i]);
}
}
query.executeUpdate();
}
//统一的添加的方法
public static void save(Object obj){
Session s=null;
Transaction tx=null;
try {
s=openSession();
tx=s.beginTransaction();
s.save(obj);
tx.commit();
} catch (Exception e) {
if(tx!=null){
tx.rollback();
}
throw new RuntimeException(e.getMessage());
// TODO: handle exception
}finally{
if(s!=null && s.isOpen()){
s.close();
}
}
}
//提供一个统一的查询方法(带分页) hql 形式 from 类 where 条件=? ..
public static List executeQueryByPage(String hql,String [] parameters,int pageSize,int pageNow){
Session s=null;
List list=null;
try {
s=openSession();
Query query=s.createQuery(hql);
//先判断是否有参数要绑定
if(parameters!=null&& parameters.length>0){
for(int i=0;i<parameters.length;i++){
query.setString(i, parameters[i]);
}
}
query.setFirstResult((pageNow-1)*pageSize).setMaxResults(pageSize);
list=query.list();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
// TODO: handle exception
}finally{
if(s!=null&&s.isOpen()){
s.close();
}
}
return list;
}
//提供一个统一的查询方法 hql 形式 from 类 where 条件=? ..
public static List executeQuery(String hql,String [] parameters){
Session s=null;
List list=null;
try {
s=openSession();
Query query=s.createQuery(hql);
//先判断是否有参数要绑定
if(parameters!=null&& parameters.length>0){
for(int i=0;i<parameters.length;i++){
query.setString(i, parameters[i]);
}
}
list=query.list();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
// TODO: handle exception
}finally{
if(s!=null&&s.isOpen()){
s.close();
}
}
return list;
}
}
package com.qq.view;
import com.qq.util.*;
import com.qq.domain.*;
import org.hibernate.Session;
import org.hibernate.Transaction;
import java.util.List;
import java.util.Iterator;
import java.util.Set;
import org.hibernate.Query;
public class TestMain {
private static Session session=null;
private static Transaction ts=null;
public static void main(String[] args){
//通过获取一个session加载cfg来创建数据库
//HibernateUtil.openSession();
Session s=null;
Transaction tx=null;
try {
//使用基础模板演示
s=HibernateUtil.getCurrentSession();
tx=s.beginTransaction();
//添加一个学生和一个部门,且把学生指定到该部门
Student stu1=new Student();
stu1.setName("孙仲谋");
Student stu2=new Student();
stu2.setName("孙策");
Department d1=new Department();
d1.setName("国防部");
Department d2=new Department();
d2.setName("财政部");
stu1.setDept(d1);
stu2.setDept(d2);
//如果先保存学生会怎么样?
//也会成功,hibernate优化了,它先把外键置空,再保存department但建议先保存主对象,再保存从对象
s.save(d1);
s.save(stu1);
s.save(d2);
s.save(stu2);
tx.commit();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
if(tx!=null){
tx.rollback();
}
}finally{
if(s!=null && s.isOpen()){
s.close();
}
}
}
}
懒加载问题
什么是懒加载?
当我们查询一个对象时,在默认情况下,返回的只是该对象的普通属性,当用户使用对象属性时,才会向数据库发出再次查询
解决办法。
①Hibernate.initialize
//显示初始代理对象
Hibernate.initialize(stu3.getDept());
②修改对象关系映射文件 Department.hbm.xml <class name="Department" lazy="false">
③通过过滤器(web项目)openSessionInview
package com.qq.view;
import com.qq.util.*;
import com.qq.domain.*;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.Hibernate;
public class TestMain {
private static Session session=null;
private static Transaction ts=null;
public static void main(String[] args){
Student stu3=getStudent();
System.out.println(stu3.getName()+" 学生所在部门:"+stu3.getDept
().getName());
}
//获取某个学生
public static Student getStudent() {
//通过获取一个session加载cfg来创建数据库
//HibernateUtil.openSession();
Student stu3=null;
Session s=null;
Transaction tx=null;
try {
//使用基础模板演示
s=HibernateUtil.getCurrentSession();
tx=s.beginTransaction();
//查询3号学生
stu3=(Student)s.get(Student.class, 3);
// System.out.println(stu3.getName()+" 学生所在部
门:"+stu3.getDept().getName());
//显示初始代理对象
// Hibernate.initialize(stu3.getDept());
tx.commit();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
if(tx!=null){
tx.rollback();
}
}finally{
if(s!=null && s.isOpen()){
s.close();
}
}
return stu3;
}
}
one to many问题
通过一个部分号获取该部门的所有学生。
<?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">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
<session-factory>
<property name="connection.username">scott</property>
<property name="connection.url">
jdbc:oracle:thin:@127.0.0.1:1521:orcl
</property>
<property name="dialect">
org.hibernate.dialect.Oracle9Dialect
</property>
<property name="connection.password">tiger</property>
<property name="connection.driver_class">
oracle.jdbc.driver.OracleDriver
</property>
<property name="show_sql">true</property>
<!-- 配置 自动创建关系模型 -->
<property name="hbm2ddl.auto">update</property>
<mapping resource="com/qq/domain/Department.hbm.xml" />
<mapping resource="com/qq/domain/Student.hbm.xml" />
</session-factory>
</hibernate-configuration>
package com.qq.domain;
public class Student implements java.io.Serializable{
private static final long serialVersionUID=1L;
private Integer id;
private String name;
private Department dept;
public Department getDept() {
return dept;
}
public void setDept(Department dept) {
this.dept = dept;
}
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;
}
}
```xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping package="com.qq.domain">
<class name="Student">
<id name="id" type="java.lang.Integer">
<generator class="sequence">
<param name="sequence">stu_seq</param>
</generator>
</id>
<property name="name" type="java.lang.String">
<column name="name" length="64"/>
</property>
<!-- 对于private Department dept就不能用property来配置了 将来自动生成的外键名
dept_id-->
<many-to-one name="dept" column="dept_id"/>
</class>
</hibernate-mapping>
package com.qq.domain;
import java.util.Set;
public class Department implements java.io.Serializable{
private static final long serialVersionUID=1L;
private Integer id;
private String name;
private Set<Student> stus;
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 Set<Student> getStus() {
return stus;
}
public void setStus(Set<Student> stus) {
this.stus = stus;
}
}
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping package="com.qq.domain">
<class name="Department">
<id name="id" type="java.lang.Integer">
<generator class="sequence">
<param name="sequence">dept_seq</param>
</generator>
</id>
<property name="name" type="java.lang.String">
<column name="name" length="64" not-null="true"/>
</property>
<!-- 配置one to many关系 stus是Department.java中的属性名称,Student是类名-->
<set name="stus" cascade="save-update">
<!-- 指定Student类对应的外键 dept_id是Student.hbm.xml中指定的外键名称-->
<key column="dept_id"/>
<one-to-many class="Student"/>
</set>
</class>
</hibernate-mapping>
package com.qq.util;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
final public class HibernateUtil {
private static SessionFactory sessionFactory=null;
//使用线程局部模式
private static ThreadLocal<Session> threadLocal=new ThreadLocal<Session>();
private HibernateUtil(){};
static {
sessionFactory=new Configuration().configure().buildSessionFactory();
}
//获取全新的全新的sesession
public static Session openSession(){
return sessionFactory.openSession();
}
//获取和线程关联的session
public static Session getCurrentSession(){
Session session=threadLocal.get();
//判断是否得到
if(session==null){
session=sessionFactory.openSession();
//把session对象设置到 threadLocal,相当于该session已经和线程绑定
threadLocal.set(session);
}
return session;
}
public static void closeCurrentSession(){
Session s=getCurrentSession();
if(s!=null&& s.isOpen() ){
s.close();
threadLocal.set(null);
}
}
//这里提供一个根据id返回对象的方法
public static Object findById(Class clazz,java.io.Serializable id){
Session s=null;
Transaction tx=null;
Object obj=null;
try {
s=openSession();
tx=s.beginTransaction();
obj=s.load(clazz, id);
tx.commit();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
// TODO: handle exception
}finally{
if(s!=null&&s.isOpen()){
s.close();
}
}
return obj;
}
//统一的一个修改和删除(批量 hql) hql"delete upate ...??"
public static void executeUpdate(String hql,String [] parameters){
Session s=null;
Transaction tx=null;
try {
s=openSession();
tx=s.beginTransaction();
Query query=s.createQuery(hql);
//先判断是否有参数要绑定
if(parameters!=null&& parameters.length>0){
for(int i=0;i<parameters.length;i++){
query.setString(i, parameters[i]);
}
}
query.executeUpdate();
tx.commit();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
// TODO: handle exception
}finally{
if(s!=null&&s.isOpen()){
s.close();
}
}
}
//如果要配置openSessionInView
//统一的一个修改和删除(批量 hql) hql"delete upate ...??"
public static void executeUpdateOpenInView(String hql,String [] parameters){
Session s=getCurrentSession();
Query query=s.createQuery(hql);
//先判断是否有参数要绑定
if(parameters!=null&& parameters.length>0){
for(int i=0;i<parameters.length;i++){
query.setString(i, parameters[i]);
}
}
query.executeUpdate();
}
//统一的添加的方法
public static void save(Object obj){
Session s=null;
Transaction tx=null;
try {
s=openSession();
tx=s.beginTransaction();
s.save(obj);
tx.commit();
} catch (Exception e) {
if(tx!=null){
tx.rollback();
}
throw new RuntimeException(e.getMessage());
// TODO: handle exception
}finally{
if(s!=null && s.isOpen()){
s.close();
}
}
}
//提供一个统一的查询方法(带分页) hql 形式 from 类 where 条件=? ..
public static List executeQueryByPage(String hql,String [] parameters,int pageSize,int pageNow){
Session s=null;
List list=null;
try {
s=openSession();
Query query=s.createQuery(hql);
//先判断是否有参数要绑定
if(parameters!=null&& parameters.length>0){
for(int i=0;i<parameters.length;i++){
query.setString(i, parameters[i]);
}
}
query.setFirstResult((pageNow-1)*pageSize).setMaxResults
(pageSize);
list=query.list();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
// TODO: handle exception
}finally{
if(s!=null&&s.isOpen()){
s.close();
}
}
return list;
}
//提供一个统一的查询方法 hql 形式 from 类 where 条件=? ..
public static List executeQuery(String hql,String [] parameters){
Session s=null;
List list=null;
try {
s=openSession();
Query query=s.createQuery(hql);
//先判断是否有参数要绑定
if(parameters!=null&& parameters.length>0){
for(int i=0;i<parameters.length;i++){
query.setString(i, parameters[i]);
}
}
list=query.list();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
// TODO: handle exception
}finally{
if(s!=null&&s.isOpen()){
s.close();
}
}
return list;
}
}
package com.qq.view;
import com.qq.util.*;
import com.qq.domain.*;
import org.hibernate.Session;
import org.hibernate.Transaction;
import java.util.HashSet;
import java.util.List;
import java.util.Iterator;
import java.util.Set;
import org.hibernate.Query;
public class TestMain {
private static Session session=null;
private static Transaction ts=null;
public static void main(String[] args){
Session session=null;
Transaction tx=null;
try {
//获取一个session加载hibernate.cfg.xml创建数据库
//HibernateUtil.openSession();
session=HibernateUtil.getCurrentSession();
tx=session.beginTransaction();
//法1
//String hql="from Student where dept.id=1";
//法2
Department department=(Department)session.get(Department.class,
3);
Set<Student> stus=department.getStus();
for(Student ss:stus){
System.out.println(ss.getName());
}
//添加学生
Department d1=new Department();
d1.setName("农业部");
Student stu1=new Student();
stu1.setName("元谋人");
Student stu2=new Student();
stu2.setName("张苞");
Set sets=new HashSet<Student>();
sets.add(stu1);sets.add(stu2);
d1.setStus(sets);
session.save(d1);
tx.commit();//提交后会自动关闭session
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
if(tx!=null){
tx.rollback();
new RuntimeException(e.getMessage());
}
}finally{
if(session!=null && session.isOpen()){
session.close();
}
}
}
}
one to one 问题
基于主键的one to one
基于外键的one to one
<?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">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
<session-factory>
<property name="connection.username">scott</property>
<property name="connection.url">
jdbc:oracle:thin:@127.0.0.1:1521:orcl
</property>
<property name="dialect">
org.hibernate.dialect.Oracle9Dialect
</property>
<property name="connection.password">tiger</property>
<property name="connection.driver_class">
oracle.jdbc.driver.OracleDriver
</property>
<property name="show_sql">true</property>
<!-- 配置 自动创建关系模型 -->
<property name="hbm2ddl.auto">update</property>
<mapping resource="com/qq/domain/Person.hbm.xml" />
<mapping resource="com/qq/domain/IdCard.hbm.xml" />
</session-factory>
</hibernate-configuration>
package com.qq.domain;
public class Person implements java.io.Serializable{
private Integer id;
private String name;
private IdCard idCard;
private static final long serialVersionUID=1L;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public IdCard getIdCard() {
return idCard;
}
public void setIdCard(IdCard idCard) {
this.idCard = idCard;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping package="com.qq.domain">
<class name="Person">
<id name="id" type="java.lang.Integer">
<generator class="assigned"/>
</id>
<property name="name" type="java.lang.String">
<column name="name" length="64" not-null="true"/>
</property>
<!-- 配置person和idCard属性的one to one 关系-->
<one-to-one name="idCard"/>
</class>
</hibernate-mapping>
package com.qq.domain;
import java.util.Date;
public class IdCard implements java.io.Serializable{
private static final long serialVersionUID=1L;
private Integer id;
private Date vaildDate;
private Person person;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
public Date getVaildDate() {
return vaildDate;
}
public void setVaildDate(Date vaildDate) {
this.vaildDate = vaildDate;
}
}
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping package="com.qq.domain">
<class name="IdCard">
<!-- one to one,so使用外键生成策略
<id name="id" type="java.lang.Integer">
<generator class="foreign">
<param name="property">person</param>
</generator>
</id>-->
<!-- 基于外键的one-to-one -->
<id name="id" type="java.lang.Integer">
<generator class="assigned"></generator>
</id>
<property name="vaildDate" type="java.util.Date">
<column name="vaildDate"/>
</property>
<!-- 配置one to one
<one-to-one name="person" constrained="true"/>-->
<many-to-one name="person" unique="true"/>
</class>
</hibernate-mapping>
package com.qq.view;
import com.qq.util.*;
import com.qq.domain.*;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class TestMain {
private static Session session=null;
private static Transaction ts=null;
public static void main(String[] args){
Session session=null;
Transaction tx=null;
try {
//获取一个session加载hibernate.cfg.xml创建数据库
//HibernateUtil.openSession();
session=HibernateUtil.getCurrentSession();
tx=session.beginTransaction();
//one to one 关系演示
Person p1=new Person();
p1.setId(16030226);
p1.setName("乐进");
IdCard id1=new IdCard();
id1.setId(5464666);
id1.setVaildDate(new Date());
id1.setPerson(p1);//表示id1对象属于p1对象
session.save(p1);
session.save(id1);
tx.commit();//提交后会自动关闭session
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
if(tx!=null){
tx.rollback();
new RuntimeException(e.getMessage());
}
}finally{
if(session!=null && session.isOpen()){
session.close();
}
}
}
}
package com.qq.util;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
final public class HibernateUtil {
private static SessionFactory sessionFactory=null;
//使用线程局部模式
private static ThreadLocal<Session> threadLocal=new ThreadLocal<Session>();
private HibernateUtil(){};
static {
sessionFactory=new Configuration().configure().buildSessionFactory();
}
//获取全新的全新的sesession
public static Session openSession(){
return sessionFactory.openSession();
}
//获取和线程关联的session
public static Session getCurrentSession(){
Session session=threadLocal.get();
//判断是否得到
if(session==null){
session=sessionFactory.openSession();
//把session对象设置到 threadLocal,相当于该session已经和线程绑定
threadLocal.set(session);
}
return session;
}
public static void closeCurrentSession(){
Session s=getCurrentSession();
if(s!=null&& s.isOpen() ){
s.close();
threadLocal.set(null);
}
}
//这里提供一个根据id返回对象的方法
public static Object findById(Class clazz,java.io.Serializable id){
Session s=null;
Transaction tx=null;
Object obj=null;
try {
s=openSession();
tx=s.beginTransaction();
obj=s.load(clazz, id);
tx.commit();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
// TODO: handle exception
}finally{
if(s!=null&&s.isOpen()){
s.close();
}
}
return obj;
}
//统一的一个修改和删除(批量 hql) hql"delete upate ...??"
public static void executeUpdate(String hql,String [] parameters){
Session s=null;
Transaction tx=null;
try {
s=openSession();
tx=s.beginTransaction();
Query query=s.createQuery(hql);
//先判断是否有参数要绑定
if(parameters!=null&& parameters.length>0){
for(int i=0;i<parameters.length;i++){
query.setString(i, parameters[i]);
}
}
query.executeUpdate();
tx.commit();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
// TODO: handle exception
}finally{
if(s!=null&&s.isOpen()){
s.close();
}
}
}
//如果要配置openSessionInView
//统一的一个修改和删除(批量 hql) hql"delete upate ...??"
public static void executeUpdateOpenInView(String hql,String [] parameters){
Session s=getCurrentSession();
Query query=s.createQuery(hql);
//先判断是否有参数要绑定
if(parameters!=null&& parameters.length>0){
for(int i=0;i<parameters.length;i++){
query.setString(i, parameters[i]);
}
}
query.executeUpdate();
}
//统一的添加的方法
public static void save(Object obj){
Session s=null;
Transaction tx=null;
try {
s=openSession();
tx=s.beginTransaction();
s.save(obj);
tx.commit();
} catch (Exception e) {
if(tx!=null){
tx.rollback();
}
throw new RuntimeException(e.getMessage());
// TODO: handle exception
}finally{
if(s!=null && s.isOpen()){
s.close();
}
}
}
//提供一个统一的查询方法(带分页) hql 形式 from 类 where 条件=? ..
public static List executeQueryByPage(String hql,String [] parameters,int
pageSize,int pageNow){
Session s=null;
List list=null;
try {
s=openSession();
Query query=s.createQuery(hql);
//先判断是否有参数要绑定
if(parameters!=null&& parameters.length>0){
for(int i=0;i<parameters.length;i++){
query.setString(i, parameters[i]);
}
}
query.setFirstResult((pageNow-1)*pageSize).setMaxResults
(pageSize);
list=query.list();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
// TODO: handle exception
}finally{
if(s!=null&&s.isOpen()){
s.close();
}
}
return list;
}
//提供一个统一的查询方法 hql 形式 from 类 where 条件=? ..
public static List executeQuery(String hql,String [] parameters){
Session s=null;
List list=null;
try {
s=openSession();
Query query=s.createQuery(hql);
//先判断是否有参数要绑定
if(parameters!=null&& parameters.length>0){
for(int i=0;i<parameters.length;i++){
query.setString(i, parameters[i]);
}
}
list=query.list();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
// TODO: handle exception
}finally{
if(s!=null&&s.isOpen()){
s.close();
}
}
return list;
}
}
many-to-many问题
购物车-商品
qq号-qq群
<?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">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
<session-factory>
<property name="connection.username">scott</property>
<property name="connection.url">
jdbc:oracle:thin:@127.0.0.1:1521:orcl
</property>
<property name="dialect">
org.hibernate.dialect.Oracle9Dialect
</property>
<property name="connection.password">tiger</property>
<property name="connection.driver_class">
oracle.jdbc.driver.OracleDriver
</property>
<property name="show_sql">true</property>
<!-- 配置 自动创建关系模型 -->
<property name="hbm2ddl.auto">update</property>
<mapping resource="com/qq/domain/StuCourse.hbm.xml" />
<mapping resource="com/qq/domain/Student.hbm.xml" />
<mapping resource="com/qq/domain/Course.hbm.xml" />
</session-factory>
</hibernate-configuration>
package com.qq.domain;
import java.util.Set;
public class Student implements java.io.Serializable{
private static final long serialVersionUID=1L;
private Integer id;
private String name;
private Set<StuCourse> stuCourses;
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 Set<StuCourse> getStuCourses() {
return stuCourses;
}
public void setStuCourses(Set<StuCourse> stuCourses) {
this.stuCourses = stuCourses;
}
}
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping package="com.qq.domain">
<class name="Student">
<id name="id" type="java.lang.Integer">
<generator class="sequence">
<param name="sequence">stu_seq</param>
</generator>
</id>
<property name="name" type="java.lang.String">
<column name="name" length="64" not-null="true"/>
</property>
<!-- 配置student和course的关系one to many一个学生可以对应多个课程-->
<set name="stuCourses">
<key column="student_id"/>
<one-to-many class="StuCourse"/>
</set>
</class>
</hibernate-mapping>
package com.qq.domain;
import java.util.Set;
public class Course {
private Integer id;
private String name;
private Set<StuCourse> stuCourses;
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 Set<StuCourse> getStuCourses() {
return stuCourses;
}
public void setStuCourses(Set<StuCourse> stuCourses) {
this.stuCourses = stuCourses;
}
}
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping package="com.qq.domain">
<class name="Course">
<id name="id" type="java.lang.Integer">
<generator class="sequence">
<param name="sequence">course_seq</param>
</generator>
</id>
<property name="name" type="java.lang.String">
<column name="name" length="64"/>
</property>
<!-- 配置one to many 一个课程可以对应多个选课记录-->
<set name="stuCourses">
<key column="course_id"/>
<one-to-many class="StuCourse"/>
</set>
</class>
</hibernate-mapping>
package com.qq.domain;
public class StuCourse {
private Integer id;
private Integer grade;
private Course course;
private Student student;
public Course getCourse() {
return course;
}
public void setCourse(Course course) {
this.course = course;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
public Integer getGrade() {
return grade;
}
public void setGrade(Integer grade) {
this.grade = grade;
}
}
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping package="com.qq.domain">
<class name="StuCourse">
<id name="id" type="java.lang.Integer">
<generator class="sequence">
<param name="sequence">stucourse_seq</param>
</generator>
</id>
<property name="grade" type="java.lang.Integer">
<column name="grade" length="3"/>
</property>
<!-- 关系-->
<many-to-one name="course" column="course_id"/>
<many-to-one name="student" column="student_id"/>
</class>
</hibernate-mapping>
package com.qq.util;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
final public class HibernateUtil {
private static SessionFactory sessionFactory=null;
//使用线程局部模式
private static ThreadLocal<Session> threadLocal=new ThreadLocal<Session>();
private HibernateUtil(){};
static {
sessionFactory=new Configuration().configure().buildSessionFactory();
}
//获取全新的全新的sesession
public static Session openSession(){
return sessionFactory.openSession();
}
//获取和线程关联的session
public static Session getCurrentSession(){
Session session=threadLocal.get();
//判断是否得到
if(session==null){
session=sessionFactory.openSession();
//把session对象设置到 threadLocal,相当于该session已经和线程绑定
threadLocal.set(session);
}
return session;
}
public static void closeCurrentSession(){
Session s=getCurrentSession();
if(s!=null&& s.isOpen() ){
s.close();
threadLocal.set(null);
}
}
//这里提供一个根据id返回对象的方法
public static Object findById(Class clazz,java.io.Serializable id){
Session s=null;
Transaction tx=null;
Object obj=null;
try {
s=openSession();
tx=s.beginTransaction();
obj=s.load(clazz, id);
tx.commit();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
// TODO: handle exception
}finally{
if(s!=null&&s.isOpen()){
s.close();
}
}
return obj;
}
//统一的一个修改和删除(批量 hql) hql"delete upate ...??"
public static void executeUpdate(String hql,String [] parameters){
Session s=null;
Transaction tx=null;
try {
s=openSession();
tx=s.beginTransaction();
Query query=s.createQuery(hql);
//先判断是否有参数要绑定
if(parameters!=null&& parameters.length>0){
for(int i=0;i<parameters.length;i++){
query.setString(i, parameters[i]);
}
}
query.executeUpdate();
tx.commit();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
// TODO: handle exception
}finally{
if(s!=null&&s.isOpen()){
s.close();
}
}
}
//如果要配置openSessionInView
//统一的一个修改和删除(批量 hql) hql"delete upate ...??"
public static void executeUpdateOpenInView(String hql,String [] parameters){
Session s=getCurrentSession();
Query query=s.createQuery(hql);
//先判断是否有参数要绑定
if(parameters!=null&& parameters.length>0){
for(int i=0;i<parameters.length;i++){
query.setString(i, parameters[i]);
}
}
query.executeUpdate();
}
//统一的添加的方法
public static void save(Object obj){
Session s=null;
Transaction tx=null;
try {
s=openSession();
tx=s.beginTransaction();
s.save(obj);
tx.commit();
} catch (Exception e) {
if(tx!=null){
tx.rollback();
}
throw new RuntimeException(e.getMessage());
// TODO: handle exception
}finally{
if(s!=null && s.isOpen()){
s.close();
}
}
}
//提供一个统一的查询方法(带分页) hql 形式 from 类 where 条件=? ..
public static List executeQueryByPage(String hql,String [] parameters,int
pageSize,int pageNow){
Session s=null;
List list=null;
try {
s=openSession();
Query query=s.createQuery(hql);
//先判断是否有参数要绑定
if(parameters!=null&& parameters.length>0){
for(int i=0;i<parameters.length;i++){
query.setString(i, parameters[i]);
}
}
query.setFirstResult((pageNow-1)*pageSize).setMaxResults
(pageSize);
list=query.list();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
// TODO: handle exception
}finally{
if(s!=null&&s.isOpen()){
s.close();
}
}
return list;
}
//提供一个统一的查询方法 hql 形式 from 类 where 条件=? ..
public static List executeQuery(String hql,String [] parameters){
Session s=null;
List list=null;
try {
s=openSession();
Query query=s.createQuery(hql);
//先判断是否有参数要绑定
if(parameters!=null&& parameters.length>0){
for(int i=0;i<parameters.length;i++){
query.setString(i, parameters[i]);
}
}
list=query.list();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
// TODO: handle exception
}finally{
if(s!=null&&s.isOpen()){
s.close();
}
}
return list;
}
}
package com.qq.view;
import com.qq.util.*;
import com.qq.domain.*;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class TestMain {
private static Session session=null;
private static Transaction ts=null;
public static void main(String[] args){
Session session=null;
Transaction tx=null;
try {
//获取一个session加载hibernate.cfg.xml创建数据库
//HibernateUtil.openSession();
session=HibernateUtil.getCurrentSession();
tx=session.beginTransaction();
//添加一个学生,一门课程
Student stu1=new Student();
stu1.setName("星彩");
Course course1=new Course();
course1.setName("Java程序设计");
StuCourse sc=new StuCourse();
sc.setCourse(course1);
sc.setStudent(stu1);
sc.setGrade(88);
//顺序保存
session.save(stu1);
session.save(course1);
session.save(sc);
tx.commit();//提交后会自动关闭session
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
if(tx!=null){
tx.rollback();
new RuntimeException(e.getMessage());
}
}finally{
if(session!=null && session.isOpen()){
session.close();
}
}
}
}
-- Create table
create table STUDENT
(
ID NUMBER(10) not null,
NAME VARCHAR2(64 CHAR) not null
)
tablespace USERS
pctfree 10
initrans 1
maxtrans 255
storage
(
initial 64K
minextents 1
maxextents unlimited
);
-- Create/Recreate primary, unique and foreign key constraints
alter table STUDENT
add primary key (ID)
using index
tablespace USERS
pctfree 10
initrans 2
maxtrans 255
storage
(
initial 64K
minextents 1
maxextents unlimited
);
-- Create table
create table COURSE
(
ID NUMBER(10) not null,
NAME VARCHAR2(64 CHAR)
)
tablespace USERS
pctfree 10
initrans 1
maxtrans 255
storage
(
initial 64K
minextents 1
maxextents unlimited
);
-- Create/Recreate primary, unique and foreign key constraints
alter table COURSE
add primary key (ID)
using index
tablespace USERS
pctfree 10
initrans 2
maxtrans 255
storage
(
initial 64K
minextents 1
maxextents unlimited
);
-- Create table
create table STUCOURSE
(
ID NUMBER(10) not null,
GRADE NUMBER(10),
COURSE_ID NUMBER(10),
STUDENT_ID NUMBER(10)
)
tablespace USERS
pctfree 10
initrans 1
maxtrans 255
storage
(
initial 64K
minextents 1
maxextents unlimited
);
-- Create/Recreate primary, unique and foreign key constraints
alter table STUCOURSE
add primary key (ID)
using index
tablespace USERS
pctfree 10
initrans 2
maxtrans 255
storage
(
initial 64K
minextents 1
maxextents unlimited
);
alter table STUCOURSE
add constraint FKCA19334F2248A6F1 foreign key (STUDENT_ID)
references STUDENT (ID);
alter table STUCOURSE
add constraint FKCA19334FFCD1D5E3 foreign key (COURSE_ID)
references COURSE (ID);