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 ...
随机推荐
- Freemarker例子
1.引入架包 2.写ftl文件 3.代码 hello.ftl 你好啊,${hello},今天你的精神不错! if else 语句测试 <#if num gt 18><#-- 不使用 ...
- jquery trigger伪造a标签的click事件取代window.open方法
$(function() { $('#btnyes').click(function () { $('#ssss').attr("href", "http://www.b ...
- getchar(),gets(),scanf()的差异比较
scanf( )函数和gets( )函数都可用于输入字符串,但在功能上有区别.若想从键盘上输入字符串"hi hello",则应该使用gets()函数. gets可以接收空格:而sc ...
- java调用存储过程和函数
以对表test进行增,删,改,查进行说明:1.新建表test create table TEST ( TID NUMBER not null, TNAME VARCHAR2(32), TCODE VA ...
- C++实现数字媒体三维图像渲染
C++实现数字媒体三维图像渲染 必备环境 glut.h 头文件 glut32.lib 对象文件库 glut32.dll 动态连接库 程序说明 C++实现了用glut画物体对象的功能.并附带放大缩小,旋 ...
- .net datatable 添加一列
dt.Columns.Add("image", Type.GetType("System.String")); foreach (DataRow dr in d ...
- Python标准库之os模块
1.删除和重命名文件 import os import string def replace(file, search_for, replace_with): # replace strings in ...
- angular-file-upload API angular文件上传插件
官方例子 : http://nervgh.github.io/pages/angular-file-upload/examples/simple/ ===Directives=== nvFileSel ...
- 管道Pipe
管道Pipe java.nio.channels包中含有一个名为Pipe(管道)的类.广义上讲,管道就是一个用来在两个实体之间单向传输数据的导管.管道的概念对于Unix(和类Unix)操作系统的用户来 ...
- Unix无缓冲文件操作函数、文件信息查询
问题描述: Unix无缓冲文件操作函数.文件信息查询 问题解决: struct stat 结构体信息: 具体代码: 具体源文件: