1.

 <?xml version="1.0"?>
<!DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping > <class name="mypack.Monkey" table="MONKEYS"> <id name="id" type="long" column="ID">
<generator class="increment"/>
</id> <property name="name" type="string" column="NAME" /> <!--
<many-to-one
name="team"
column="TEAM_ID"
class="mypack.Team"
lazy="false"
/>
--> <!-- mapping with cascade -->
<!---->
<many-to-one
name="team"
column="TEAM_ID"
class="mypack.Team"
cascade="save-update"
lazy="false"
/> </class> </hibernate-mapping>

2.

 package mypack;
public class Monkey{
private long id;
private String name;
private Team team; public Monkey() {}
public Monkey(String name, Team team) {
this.name = name;
this.team = team;
} public long getId() {
return this.id;
} public void setId(long id) {
this.id = id;
}
public String getName() {
return this.name;
} public void setName(String name) {
this.name = name;
}
public Team getTeam() {
return this.team;
} public void setTeam(Team team) {
this.team = team;
} }

3.

 <?xml version="1.0"?>
<!DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping > <class name="mypack.Team" table="TEAMS" >
<id name="id" type="long" column="ID">
<generator class="increment"/>
</id> <property name="name" type="string" column="NAME" /> </class> </hibernate-mapping>

4.

 package mypack;
public class Team {
private long id;
private String name; public Team() {
} public Team(String name) {
this.name = name;
} public long getId() {
return this.id;
} public void setId(long id) {
this.id = id;
}
public String getName() {
return this.name;
} public void setName(String name) {
this.name = name;
} }

5.

 package mypack;

 import org.hibernate.*;
import org.hibernate.cfg.Configuration;
import java.util.*; public class BusinessService{
public static SessionFactory sessionFactory;
static{
try{
// Create a configuration based on the properties file we've put
Configuration config = new Configuration();
config.configure();
sessionFactory = config.buildSessionFactory();
}catch(RuntimeException e){e.printStackTrace();throw e;}
} public List findMonkeysByTeam(Team team){
Session session = sessionFactory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction(); List monkeys=session.createQuery("from Monkey as m where m.team.id="+team.getId())
.list();
tx.commit();
return monkeys;
}catch (RuntimeException e) {
if (tx != null) {
tx.rollback();
}
throw e;
} finally {
session.close();
}
} public Team findTeam(long team_id){
Session session = sessionFactory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Team team=(Team)session.get(Team.class,new Long(team_id));
tx.commit();
return team;
}catch (RuntimeException e) {
if (tx != null) {
tx.rollback();
}
throw e;
} finally {
session.close();
}
} public void saveTeamAndMonkeyWithCascade(){
Session session = sessionFactory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction(); Team team=new Team("BULL");
Monkey monkey1=new Monkey("Tom",team);
Monkey monkey2=new Monkey("Mike",team); session.save(monkey1);
session.save(monkey2); tx.commit(); }catch (RuntimeException e) {
if (tx != null) {
tx.rollback();
}
e.printStackTrace();
} finally {
session.close();
}
} public void saveTeamAndMonkey(){
Session session = sessionFactory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction(); Team team=new Team("DREAM");
session.save(team); Monkey monkey1=new Monkey("Jack",team);
Monkey monkey2=new Monkey("Bill",team);
session.save(monkey1);
session.save(monkey2);
tx.commit(); }catch (RuntimeException e) {
if (tx != null) {
tx.rollback();
}
throw e;
} finally {
session.close();
}
} public void printMonkeys(List monkeys){
for (Iterator it = monkeys.iterator(); it.hasNext();) {
Monkey monkey=(Monkey)it.next();
System.out.println("Monkeys in "+monkey.getTeam().getName()+ " :"+monkey.getName());
}
} public void test(){
saveTeamAndMonkey();
saveTeamAndMonkeyWithCascade();
Team team=findTeam(1);
List monkeys=findMonkeysByTeam(team);
printMonkeys(monkeys);
} public static void main(String args[]){
new BusinessService().test();
sessionFactory.close();
}
}

6.

 <?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE hibernate-configuration
PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/sampledb
</property>
<property name="connection.username">
root
</property>
<property name="connection.password">
1234
</property>
<property name="show_sql">true</property>
<mapping resource="mypack/Team.hbm.xml" />
<mapping resource="mypack/Monkey.hbm.xml" />
</session-factory>
</hibernate-configuration>

7.

 drop database if exists SAMPLEDB;
create database SAMPLEDB;
use SAMPLEDB; create table TEAMS (
ID bigint not null,
NAME varchar(15),
primary key (ID)); create table MONKEYS (
ID bigint not null,
NAME varchar(15),
TEAM_ID bigint,
primary key (ID)); alter table MONKEYS add index IDX_TEAM(TEAM_ID),
add constraint FK_TEAM foreign key (TEAM_ID) references TEAMS (ID);

8.

 <?xml version="1.0"?>
<project name="Learning Hibernate" default="prepare" basedir="."> <!-- Set up properties containing important project directories -->
<property name="source.root" value="5.1/src"/>
<property name="class.root" value="5.1/classes"/>
<property name="lib.dir" value="lib"/>
<property name="schema.dir" value="5.1/schema"/> <!-- Set up the class path for compilation and execution -->
<path id="project.class.path">
<!-- Include our own classes, of course -->
<pathelement location="${class.root}" />
<!-- Include jars in the project library directory -->
<fileset dir="${lib.dir}">
<include name="*.jar"/>
</fileset>
</path> <!-- Create our runtime subdirectories and copy resources into them -->
<target name="prepare" description="Sets up build structures">
<delete dir="${class.root}"/>
<mkdir dir="${class.root}"/> <!-- Copy our property files and O/R mappings for use at runtime -->
<copy todir="${class.root}" >
<fileset dir="${source.root}" >
<include name="**/*.properties"/>
<include name="**/*.hbm.xml"/>
<include name="**/*.cfg.xml"/>
</fileset>
</copy>
</target> <!-- Compile the java source of the project -->
<target name="compile" depends="prepare"
description="Compiles all Java classes">
<javac srcdir="${source.root}"
destdir="${class.root}"
debug="on"
optimize="off"
deprecation="on">
<classpath refid="project.class.path"/>
</javac>
</target> <target name="run" description="Run a Hibernate sample"
depends="compile">
<java classname="mypack.BusinessService" fork="true">
<classpath refid="project.class.path"/>
</java>
</target> </project>

9.TransientObjectException

Hibernate逍遥游记-第5章映射一对多-01单向<many-to-one>、cascade="save-update"、lazy、TransientObjectException的更多相关文章

  1. Hibernate逍遥游记-第5章映射一对多-02双向(<set>、<key>、<one-to-many>、inverse、cascade="all-delete-orphan")

    1. <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hi ...

  2. Hibernate逍遥游记-第13章 映射实体关联关系-003单向多对多

    0. 1. drop database if exists SAMPLEDB; create database SAMPLEDB; use SAMPLEDB; create table MONKEYS ...

  3. Hibernate逍遥游记-第13章 映射实体关联关系-006双向多对多(分解为一对多)

    1. 2. <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate ...

  4. Hibernate逍遥游记-第13章 映射实体关联关系-005双向多对多(使用组件类集合\<composite-element>\)

    1. <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hi ...

  5. Hibernate逍遥游记-第13章 映射实体关联关系-004双向多对多(inverse="true")

    1. <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hi ...

  6. Hibernate逍遥游记-第13章 映射实体关联关系-002用主键映射一对一(<one-to-one constrained="true">、<generator class="foreign">)

    1. <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hi ...

  7. Hibernate逍遥游记-第13章 映射实体关联关系-001用外键映射一对一(<many-to-one unique="true">、<one-to-one>)

    1. <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hi ...

  8. Hibernate逍遥游记-第12章 映射值类型集合-005对集合排序Map(<order-by>\<sort>)

    1. <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hi ...

  9. Hibernate逍遥游记-第12章 映射值类型集合-005对集合排序(<order-by>\<sort>)

    1. 2. <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate ...

随机推荐

  1. JAVA多线程学习1

    一.进程与线程 线程是指进程内的一个执行单元(可理解为程序内的一条执行路径),也是进程内的可调度实体. 线程与进程的区别: 1.线程是进程的一个执行单元,一个进程可以拥有多个线程,线程之间共享进程的地 ...

  2. DBCC Check

    DBCC CHECKDB 可以完成两个任务 (1)检查数据库里有没有损坏发生 (2)尽力修复数据库损坏,是数据能重新被正常访问 DBCC 下列步骤执行下列操作 1.检查一些关键性的表 sysalocu ...

  3. gif修改背景透明

    1.用ImageReady打开,将选中所有帧,右键选择“恢复为背景”. 2.打开“颜色板”,点击左下角的惊叹号,用吸色器点击背景,颜色板自动选中了背景色,将其映射为透明. 3.文件->将优化结果 ...

  4. Access

    一般系统的实现: 管理系统的分析与设计 --->>数据表的设计创建 --->> 设计“查询”与“宏” --->> 创建窗体与报表 --->>系统注册 启 ...

  5. JPA学习---第六节:大数据字段映射与字段延迟加载

    1.大数据字段所需的注解 @Lob ,例如: @Lobprivate String info; 在mysql中映射产生的字段的类型是longtext:在oracle中是  CLOB @Lobpriva ...

  6. 送给那些喜欢myeclipse黑色主题但是又不知道怎么配色的人

    设置MyEclipse黑色主题背景 1. 下载 http://eclipsecolorthemes.org/  看哪个合适直接点击进入, 下载右边的epf 2. 下载完成...打开myeclipse. ...

  7. InnoDB与UUID

    CakePHP本身有一个uuid实现,所以一直以来,我都在尝试使用uuid做主键的可能性.虽然MySQL是我最常用的数据库,但是和 auto_increment_int主键相比,我对uuid主键更有好 ...

  8. Codeforces Round #347 (Div. 2) C. International Olympiad 找规律

    题目链接: http://codeforces.com/contest/664/problem/C 题解: 这题最关键的规律在于一位的有1989-1998(9-8),两位的有1999-2098(99- ...

  9. PE文件结构详解(五)延迟导入表

    PE文件结构详解(四)PE导入表讲 了一般的PE导入表,这次我们来看一下另外一种导入表:延迟导入(Delay Import).看名字就知道,这种导入机制导入其他DLL的时机比较“迟”,为什么要迟呢?因 ...

  10. spoj 78

    数学  组合 隔板法 #include <iostream> #include <cstring> #include <cstdio> #include <s ...