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 ...
随机推荐
- CENTOS6.2系统日志rsyslog替换默认的日志服务syslog 转载自http://www.phpboy.net/linux/648.html
最近遇到配置centos 6.2的sshd及sftp日志,发现/etc/syslog.conf文件不存在, 然后: #rpm -qa | grep syslog 出来的是 rsyslog-5.8.10 ...
- Requests库的几种请求 - 通过API操作Github
本文内容来源:https://www.dataquest.io/mission/117/working-with-apis 本文的数据来源:https://en.wikipedia.org/wiki/ ...
- Selenium-RC Python 2.7 环境配置
1.下载并安装Python http://www.python.org/getit/,我使用的是2.7.3的python版本 2.下载并安装setuptools[这个工具是python的基础包工具] ...
- iOS中的堆(heap)和栈(stack)的理解
操作系统iOS 中应用程序使用的计算机内存不是统一分配空间,运行代码使用的空间在三个不同的内存区域,分成三个段:“text segment “,“stack segment ”,“heap segme ...
- 暂停更新Blog
今天非常不好意思的是老魏又要一次的暂停文章跟新了,原因是有些有问题老魏需要从新的梳理,加上这几天工作又开始忙碌起来了,所以这一阵子估计很难有有时间更新了. 不过老魏会抽一下时间更新文章的,不可能像2月 ...
- 关于const
1.顶层const和底层const const修饰的对象本身是常量,则为顶层const,否则为底层const 如: const int a=10; //a是int常量,顶层const i ...
- [SC] OpenSCManager FAILED 1722
在服务器A(windows server 2008 r2)执行如下命令访问远端服务器B(windows server 2003)的服务运行状况: sc \\servername query " ...
- WPF 多线程处理(1)
WPF 多线程处理(1) WPF 多线程处理(2) WPF 多线程处理(3) WPF 多线程处理(4) WPF 多线程处理(5) WPF 多线程处理(6) 废话不多说,先上图: 多线程处理数据后在th ...
- bnuoj 25659 A Famous City (单调栈)
http://www.bnuoj.com/bnuoj/problem_show.php?pid=25659 #include <iostream> #include <stdio.h ...
- PHP Cookie处理函数
(o゜▽゜)o☆[BINGO!] ok,我们先看看cookie是什么东东? cookie是服务器留在客户端的用于识别用户或者存储一些数据的小文件(注意,session存储在服务器端,这是两者的区别之一 ...