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

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的更多相关文章
- Hibernate逍遥游记-第5章映射一对多-02双向(<set>、<key>、<one-to-many>、inverse、cascade="all-delete-orphan")
1. <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hi ...
- Hibernate逍遥游记-第13章 映射实体关联关系-003单向多对多
0. 1. drop database if exists SAMPLEDB; create database SAMPLEDB; use SAMPLEDB; create table MONKEYS ...
- Hibernate逍遥游记-第13章 映射实体关联关系-006双向多对多(分解为一对多)
1. 2. <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate ...
- Hibernate逍遥游记-第13章 映射实体关联关系-005双向多对多(使用组件类集合\<composite-element>\)
1. <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hi ...
- Hibernate逍遥游记-第13章 映射实体关联关系-004双向多对多(inverse="true")
1. <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hi ...
- Hibernate逍遥游记-第13章 映射实体关联关系-002用主键映射一对一(<one-to-one constrained="true">、<generator class="foreign">)
1. <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hi ...
- Hibernate逍遥游记-第13章 映射实体关联关系-001用外键映射一对一(<many-to-one unique="true">、<one-to-one>)
1. <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hi ...
- Hibernate逍遥游记-第12章 映射值类型集合-005对集合排序Map(<order-by>\<sort>)
1. <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hi ...
- Hibernate逍遥游记-第12章 映射值类型集合-005对集合排序(<order-by>\<sort>)
1. 2. <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate ...
随机推荐
- DataSnap数据库连接池,数据集对象池的应用
传统的应用服务器的开发往往是在ServerMethods单元中拖放一堆TDataSet, TDaTaSetProvider控件,这是一个最简单粗暴的开发方向,往往会造成服务端程序文件的臃肿.服务运行期 ...
- hibernate数据库配置
在文件夹etc中 ## MySQL #hibernate.dialect org.hibernate.dialect.MySQLDialect #hibernate.dialect org.hiber ...
- postgresql 开启远程访问
1.如果服务器启用了防火墙,需要在防火墙上开启 5432 端口. 2.修改 PostgreSQL 配置文件 postgresql.conf.postgresql.conf,Linux 配置文件所在路径 ...
- linux下bus,device,driver三者关系
linux下bus,device,driver三者关系 1.bus: 总线作为主机和外设的连接通道,有些总线是比较规范的,形成了很多协议.如 PCI,USB,1394,IIC等.任何设备都可以选择合适 ...
- 【nodejs】 npm 注意事项
官网:https://www.npmjs.com/ 1.安装时要切换到nodejs根目录, 否则就会安装到安装时所在的目录 2.要有管理员权限(win),如需指定版本,如npm install ex ...
- 时序图 Sequence Diagram
时序图(Sequence Diagram)是显示对象之间交互的图,这些对象是按时间顺序排列的. 时序图中显示的是参与交互的对象及其对象之间消息交互的顺序. 下面这张图介绍了时序图的基本内容: 下面这张 ...
- Export Farm Solution wsp Files SharePoint 2007 and 2010
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")$farm = [Microsof ...
- Careercup - Facebook面试题 - 5998719358992384
2014-05-02 00:22 题目链接 原题: Given a matrix consisting of 's. 题目:给定一个01矩阵,找出由1构成的连通分量中最大的一个. 解法:四邻接还是八邻 ...
- ADT通过svn进行团队开发,svn插件不好使的解决方案
在使用ADT的svn插件的时候老是会出现各种异常,所以就干脆不用svn插件了,直接将adt的工作空间建在svn上面,以保证团队成员共用一套代码,节约宝贵的整合时间. 使用步骤: 1.首先需要安装好sv ...
- 3142:[HNOI2013]数列 - BZOJ
题目描述 Description 小T最近在学着买股票,他得到内部消息:F公司的股票将会疯涨. 股票每天的价格已知是正整数,并且由于客观上的原因,最多只能为N.在疯涨的K天中小T观察到:除第一天外每天 ...