08-07
04
Hibernate实现one-to-one级联保存[自己总结]
作者:Java伴侣 日期:2008-07-04
在具体的项目应用中,我们很少会用到一对一的级联操作,且很多时候一对一的操作可以通过多对一实现,但是一对一有自己的好处,就是在任何时候都能保证主外键数据的一致性,但是多对一的情况下未必能做到.
我在项目中具体用到了一对一的级联操作,从网上拿了 一个例子来做,但是没有成功,于是只好自己研究,现在把修改后的代码帖出来.
本例子使用hibernate3.jar+oracle数据库
库表:
TestMain.java
Card.java
User.java
HibernateSessionFactory.java
Card.hbm.xml
User.hbm.xml
我在项目中具体用到了一对一的级联操作,从网上拿了 一个例子来做,但是没有成功,于是只好自己研究,现在把修改后的代码帖出来.
本例子使用hibernate3.jar+oracle数据库
库表:
引用内容
CARD_TEST(CARDID[NUMBER(18)],CARDNUM[VARCHAR2(20)])
USER_TEST(USERID[NUMBER(18)],USERNAME[VARCHAR2(20)])
USER_TEST(USERID[NUMBER(18)],USERNAME[VARCHAR2(20)])
TestMain.java
复制内容到剪贴板 程序代码
package com.gpdi.test;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class TestMain {
/**
* 存储一个用户
* @param user
*/
public void save(User user){
user.setUsername("TEST");
Card card=new Card();
//Card card1=new Card();
card.setCardnum("HGJUYT");
//card1.setCardnum("fghy55");
user.setCard(card);
//user.setCard(card1);
Session session=HibernateSessionFactory.currentSession();
card.setUser(user);
//card1.setUser(user);
Transaction tr=session.beginTransaction();
session.save(user);
//session.save(card);
tr.commit();
session.close();
}
public static void main(String[] args) throws Exception {
TestMain test=new TestMain();
test.save(new User());
}
}
import org.hibernate.Session;
import org.hibernate.Transaction;
public class TestMain {
/**
* 存储一个用户
* @param user
*/
public void save(User user){
user.setUsername("TEST");
Card card=new Card();
//Card card1=new Card();
card.setCardnum("HGJUYT");
//card1.setCardnum("fghy55");
user.setCard(card);
//user.setCard(card1);
Session session=HibernateSessionFactory.currentSession();
card.setUser(user);
//card1.setUser(user);
Transaction tr=session.beginTransaction();
session.save(user);
//session.save(card);
tr.commit();
session.close();
}
public static void main(String[] args) throws Exception {
TestMain test=new TestMain();
test.save(new User());
}
}
Card.java
复制内容到剪贴板 程序代码
package com.gpdi.test;
/**
* Card generated by MyEclipse - Hibernate Tools
*/
public class Card implements java.io.Serializable {
// Fields
private Integer cardid;
private String cardnum;
private User user;
// Constructors
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
/** default constructor */
public Card() {
}
/** full constructor */
public Card(String cardnum) {
this.cardnum = cardnum;
}
// Property accessors
public Integer getCardid() {
return this.cardid;
}
public void setCardid(Integer cardid) {
this.cardid = cardid;
}
public String getCardnum() {
return this.cardnum;
}
public void setCardnum(String cardnum) {
this.cardnum = cardnum;
}
}
/**
* Card generated by MyEclipse - Hibernate Tools
*/
public class Card implements java.io.Serializable {
// Fields
private Integer cardid;
private String cardnum;
private User user;
// Constructors
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
/** default constructor */
public Card() {
}
/** full constructor */
public Card(String cardnum) {
this.cardnum = cardnum;
}
// Property accessors
public Integer getCardid() {
return this.cardid;
}
public void setCardid(Integer cardid) {
this.cardid = cardid;
}
public String getCardnum() {
return this.cardnum;
}
public void setCardnum(String cardnum) {
this.cardnum = cardnum;
}
}
User.java
复制内容到剪贴板 程序代码
package com.gpdi.test;
import java.util.HashSet;
import java.util.Set;
/**
* User generated by MyEclipse - Hibernate Tools
*/
public class User implements java.io.Serializable {
// Fields
private Integer userid;
private String username;
private Card card;
//private Set card = new HashSet();
// Constructors
public Card getCard() {
return card;
}
public void setCard(Card card) {
this.card = card;
}
/** default constructor */
public User() {
}
/** full constructor */
public User(String username) {
this.username = username;
}
// Property accessors
public Integer getUserid() {
return this.userid;
}
public void setUserid(Integer userid) {
this.userid = userid;
}
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
}
import java.util.HashSet;
import java.util.Set;
/**
* User generated by MyEclipse - Hibernate Tools
*/
public class User implements java.io.Serializable {
// Fields
private Integer userid;
private String username;
private Card card;
//private Set card = new HashSet();
// Constructors
public Card getCard() {
return card;
}
public void setCard(Card card) {
this.card = card;
}
/** default constructor */
public User() {
}
/** full constructor */
public User(String username) {
this.username = username;
}
// Property accessors
public Integer getUserid() {
return this.userid;
}
public void setUserid(Integer userid) {
this.userid = userid;
}
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
}
HibernateSessionFactory.java
复制内容到剪贴板 程序代码
package com.gpdi.test;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
/**
* Configures and provides access to Hibernate sessions, tied to the
* current thread of execution. Follows the Thread Local Session
* pattern, see {@link http://hibernate.org/42.html}.
*/
public class HibernateSessionFactory {
/**
* Location of hibernate.cfg.xml file.
* NOTICE: Location should be on the classpath as Hibernate uses
* #resourceAsStream style lookup for its configuration file. That
* is place the config file in a Java package - the default location
* is the default Java package.<br><br>
* Examples: <br>
* <code>CONFIG_FILE_LOCATION = "/hibernate.conf.xml".
* CONFIG_FILE_LOCATION = "/com/foo/bar/myhiberstuff.conf.xml".</code>
*/
private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
/** Holds a single instance of Session */
private static final ThreadLocal threadLocal = new ThreadLocal();
/** The single instance of hibernate configuration */
private static final Configuration cfg = new Configuration();
/** The single instance of hibernate SessionFactory */
private static org.hibernate.SessionFactory sessionFactory;
/**
* Returns the ThreadLocal Session instance. Lazy initialize
* the <code>SessionFactory</code> if needed.
*
* @return Session
* @throws HibernateException
*/
public static Session currentSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
try {
cfg.configure(CONFIG_FILE_LOCATION);
sessionFactory = cfg.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
}
return session;
}
/**
* Close the single hibernate session instance.
*
* @throws HibernateException
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
/**
* Default constructor.
*/
private HibernateSessionFactory() {
}
}
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
/**
* Configures and provides access to Hibernate sessions, tied to the
* current thread of execution. Follows the Thread Local Session
* pattern, see {@link http://hibernate.org/42.html}.
*/
public class HibernateSessionFactory {
/**
* Location of hibernate.cfg.xml file.
* NOTICE: Location should be on the classpath as Hibernate uses
* #resourceAsStream style lookup for its configuration file. That
* is place the config file in a Java package - the default location
* is the default Java package.<br><br>
* Examples: <br>
* <code>CONFIG_FILE_LOCATION = "/hibernate.conf.xml".
* CONFIG_FILE_LOCATION = "/com/foo/bar/myhiberstuff.conf.xml".</code>
*/
private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
/** Holds a single instance of Session */
private static final ThreadLocal threadLocal = new ThreadLocal();
/** The single instance of hibernate configuration */
private static final Configuration cfg = new Configuration();
/** The single instance of hibernate SessionFactory */
private static org.hibernate.SessionFactory sessionFactory;
/**
* Returns the ThreadLocal Session instance. Lazy initialize
* the <code>SessionFactory</code> if needed.
*
* @return Session
* @throws HibernateException
*/
public static Session currentSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
try {
cfg.configure(CONFIG_FILE_LOCATION);
sessionFactory = cfg.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
}
return session;
}
/**
* Close the single hibernate session instance.
*
* @throws HibernateException
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
/**
* Default constructor.
*/
private HibernateSessionFactory() {
}
}
Card.hbm.xml
复制内容到剪贴板 程序代码
<?xml version="1.0"?>
<!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 - Hibernate Tools
-->
<hibernate-mapping>
<class name="com.gpdi.test.Card" table="CARD_TEST">
<id name="cardid" type="integer">
<column name="CARDID" />
<generator class="foreign" >
<param name="property">user</param>
</generator>
</id>
<property name="cardnum" type="string">
<column name="CARDNUM" length="45" not-null="true" />
</property>
<!--
foreign-key="userid"指定外键关联的字段,必须,不可缺少 ,cascade="save-update"指定怎么操作级联,非必须
-->
<one-to-one name="user" foreign-key="userid" class="com.gpdi.test.User" cascade="save-update"></one-to-one>
</class>
</hibernate-mapping>
<!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 - Hibernate Tools
-->
<hibernate-mapping>
<class name="com.gpdi.test.Card" table="CARD_TEST">
<id name="cardid" type="integer">
<column name="CARDID" />
<generator class="foreign" >
<param name="property">user</param>
</generator>
</id>
<property name="cardnum" type="string">
<column name="CARDNUM" length="45" not-null="true" />
</property>
<!--
foreign-key="userid"指定外键关联的字段,必须,不可缺少 ,cascade="save-update"指定怎么操作级联,非必须
-->
<one-to-one name="user" foreign-key="userid" class="com.gpdi.test.User" cascade="save-update"></one-to-one>
</class>
</hibernate-mapping>
User.hbm.xml
复制内容到剪贴板 程序代码
<?xml version="1.0"?>
<!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 - Hibernate Tools
-->
<hibernate-mapping>
<class name="com.gpdi.test.User" table="USER_TEST">
<id name="userid" type="integer">
<column name="USERID" />
<generator class="increment"/>
</id>
<property name="username" type="string">
<column name="username" length="45" not-null="true" />
</property>
<one-to-one name="card" foreign-key="cardid" class="com.gpdi.test.Card" cascade="save-update"></one-to-one>
<!--
<set name="card" inverse="true" cascade="all">
<key column="cardid" />
<one-to-many class="com.gpdi.test.Card" />
</set>
<many-to-one name="card" class="com.gpdi.test.Card" insert="true" unique="true" lazy="false">
<column name="cardid" length="18" />
</many-to-one>
-->
</class>
</hibernate-mapping>
<!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 - Hibernate Tools
-->
<hibernate-mapping>
<class name="com.gpdi.test.User" table="USER_TEST">
<id name="userid" type="integer">
<column name="USERID" />
<generator class="increment"/>
</id>
<property name="username" type="string">
<column name="username" length="45" not-null="true" />
</property>
<one-to-one name="card" foreign-key="cardid" class="com.gpdi.test.Card" cascade="save-update"></one-to-one>
<!--
<set name="card" inverse="true" cascade="all">
<key column="cardid" />
<one-to-many class="com.gpdi.test.Card" />
</set>
<many-to-one name="card" class="com.gpdi.test.Card" insert="true" unique="true" lazy="false">
<column name="cardid" length="18" />
</many-to-one>
-->
</class>
</hibernate-mapping>
评论: 0 | 引用: 0 | 查看次数: 870
发表评论