Hibernate annotation 一对一的两种实现:

1)幅表中有主表的主键ID做为引用

2)幅表的主键即为主表的ID


hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://127.0.0.1/testdb</property>
<property name="connection.username">root</property>
<property name="connection.password"></property> <!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property> <!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property> <!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property> <!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property> <!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property> <!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property> <mapping class="com.my.bean.User"/>
<mapping class="com.my.bean.UserCard"/>
<mapping class="com.my.bean.UserInfo"/> </session-factory> </hibernate-configuration>

HibernateUtil.java

package com.my.dao.util;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration; public class HibernateUtil { private static final SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
Configuration configuration = new Configuration();
return configuration.configure().buildSessionFactory(
new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build());
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
} public static SessionFactory getSessionFactory() {
return sessionFactory;
} }

Java Beans:

package com.my.bean;

import java.util.Date;

import javax.persistence.*;

@Entity
@Table(name="user")
public class User {
@Id @GeneratedValue @Column(name="user_id", nullable=false)
private long userID; @Column(name="user_name", length=100, nullable=false)
private String userName; @Column(name="create_time", nullable=false)
private Date createTime; @OneToOne(mappedBy="user")
private UserCard userCard; @OneToOne(cascade=CascadeType.ALL)
@PrimaryKeyJoinColumn
private UserInfo userInfo; public long getUserID() {
return userID;
} public void setUserID(long userID) {
this.userID = userID;
} public String getUserName() {
return userName;
} public void setUserName(String userName) {
this.userName = userName;
} public Date getCreateTime() {
return createTime;
} public void setCreateTime(Date createTime) {
this.createTime = createTime;
} public UserCard getUserCard() {
return userCard;
} public void setUserCard(UserCard userCard) {
this.userCard = userCard;
}
}
package com.my.bean;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table; @Entity
@Table(name="user_card")
public class UserCard {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="card_id", nullable=false)
private long cardID; @OneToOne
@JoinColumn(name="user_id")
private User user; @Column(name="card_name", nullable=false)
private String cardName; public long getCardID() {
return cardID;
}
public void setCardID(long cardID) {
this.cardID = cardID;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getCardName() {
return cardName;
}
public void setCardName(String cardName) {
this.cardName = cardName;
}
}
package com.my.bean;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter; @Entity
@Table(name="user_info")
public class UserInfo {
@Id
@GeneratedValue(generator="userInfoForeignKey")
@GenericGenerator(name="userInfoForeignKey", strategy="foreign", parameters=@Parameter(name="property", value="user"))
@Column(name="user_id", nullable=false)
private long userID; @Column(name="message", nullable=false)
private String Message; @OneToOne(mappedBy="userInfo")
private User user; public long getUserID() {
return userID;
} public void setUserID(long userID) {
this.userID = userID;
} public String getMessage() {
return Message;
} public void setMessage(String message) {
Message = message;
} public User getUser() {
return user;
} public void setUser(User user) {
this.user = user;
}
}

测试:

package com.my.init;
import java.util.Date; import org.hibernate.Session;
import org.hibernate.Transaction; import com.my.bean.User;
import com.my.bean.UserCard;
import com.my.bean.UserInfo;
import com.my.dao.util.HibernateUtil; public class Test { public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = session.beginTransaction(); try {
//---------------------------------------------------------
// The first method
//---------------------------------------------------------
// add user
User user = new User();
user.setUserName("Robin");
user.setCreateTime(new Date()); // add user card
UserCard userCard = new UserCard();
userCard.setCardName("BBC"); // add user card to user object
user.setUserCard(userCard);
userCard.setUser(user); //---------------------------------------------------------
// The second method
//---------------------------------------------------------
UserInfo userInfo = new UserInfo();
userInfo.setMessage("Message");
userInfo.setUser(user); //---------------------------------------------------------
// save
//---------------------------------------------------------
session.save(user);
session.save(userCard);
session.save(userInfo); tx.commit();
} catch (Exception e) {
tx.rollback();
e.printStackTrace();
} session.close();
} }

[Hibernate] - Annotations - One To One的更多相关文章

  1. [Hibernate] - Annotations - Many To Many

    Hibernate annotation 多对多: 下面测试例子会自动生成一张表:card,这张是bank和user表的映射表.里头是bank_id和user_id两个组合字段. 如果想在这张映射表中 ...

  2. JavaPersistenceWithHibernate第二版笔记-第五章-Mapping value types-007UserTypes的用法(@org.hibernate.annotations.Type、@org.hibernate.annotations.TypeDefs、CompositeUserType、DynamicParameterizedType、、、)

    一.结构 二.Hibernate支持的UserTypes接口  UserType —You can transform values by interacting with the plain JD ...

  3. JavaPersistenceWithHibernate第二版笔记-第五章-Mapping value types-005控制类型映射(Nationalized、@LOB、@org.hibernate.annotations.Type)

    一.简介 1. 2. 3. 4. to override this default mapping. The JPA specification has a convenient shortcut a ...

  4. java.lang.ClassNotFoundException: org.hibernate.annotations.common.reflection.MetadataProvider

    Caused by: java.lang.NoClassDefFoundError: org/hibernate/annotations/common/reflection/MetadataProvi ...

  5. BAE 环境下 hibernate annotations 配置

     annotations 配置 首先需要加入 hibernate-jpa-2.0-api-1.0.1.Final.jar 和 ejb3-persistence.jar 这两个包 ejb3-persis ...

  6. Caused by: java.lang.ClassNotFoundException: org.hibernate.annotations.common.reflection.MetadataPro

    1.错误描述 信息: MLog clients using java 1.4+ standard logging. 2014-7-12 19:29:20 com.mchange.v2.c3p0.C3P ...

  7. Hibernate Annotations 注解

    Hibernate Annotations 注解 对于org.hibernate.annotations与org.hibernate.persistence,它的注释比如Columns,可是不知道怎么 ...

  8. [Hibernate] - Annotations

    Hibernate使用Annotations最简单例子: hibernate.cfg.xml <?xml version="1.0" encoding="UTF-8 ...

  9. [Hibernate] - Annotations - One To Many

    Hibernate使用Annotation的一对多: hibernate.cfg.xml <?xml version="1.0" encoding="UTF-8&q ...

随机推荐

  1. 深度理解Key-Value Observing 键值观察

    前言   在上一阶段的开发过程中,我们大量使用了 KVO 机制,来确保页面信息的及时同步.也因此碰到了很多问题,促使我们去进一步学习 KVO 的相关机制,再到寻找更好的解决方案.鉴于 KVO 让人欲仙 ...

  2. csdn第四名

    编号:1027时间:2016年7月18日11:10:42功能:csdn第四名URL :http://blog.csdn.net/yuanmeng001

  3. cocos2d-html5如何更改预加载时的默认的logo图片和删除loading小圈圈

    找到框架目录(2.1.4)里的cocos2d目录里有个CCLoader.js文件,找到LoaderScene的构造方法ctor,可以看到有一行: this._logoTexture.src= &quo ...

  4. 线性函数拟合R语言示例

    线性函数拟合(y=a+bx) 1.       R运行实例 R语言运行代码如下:绿色为要提供的数据,黄色标识信息为需要保存的. x<-c(0.10,0.11, 0.12, 0.13, 0.14, ...

  5. Open vSwitch简述

    一.基础术语 1.Packet (数据包):网络转发的最小数据单元,每个包都来自某个端口,最终会被发往一个或多个目标端口,转发数据包的过程就是网络的唯一功能. 2.Bridge (网桥):Open v ...

  6. 从Wordpress迁移到Jekyll

    http://pinkyjie.com/2013/10/24/migrate-from-wordpress-to-jekyll/ 上周末闲着没事干突然想把博客从Wordpress迁移到Github p ...

  7. c 深度剖析 6

    函数的编码风格 1.注释 2,空行 3,缩进 4,参数长度,代码长度,语句长度要合适. 5,少用全局变量 6,指针仅作输入参数时,可用const 设置其为只读属性,避免其在函数中被修改. 7,函数默认 ...

  8. 工作中遇到的问题--Hibernate注解添加在一方和多方的区别

    以Good和GoodStatus为例: 一.注解仅添加在一方: @Entity@Table(name = "GOOD")@Where(clause="enabled=1& ...

  9. JS 的线程、事件循环、任务队列简介

    JS 是单线程的,但是却能执行异步任务,这主要是因为 JS 中存在事件循环(Event Loop)和任务队列(Task Queue). 事件循环:JS 会创建一个类似于 while (true) 的循 ...

  10. Linux驱动设计—— 中断与时钟

    中断和时钟技术可以提升驱动程序的效率 中断 中断在Linux中的实现 通常情况下,一个驱动程序只需要申请中断,并添加中断处理函数就可以了,中断的到达和中断函数的调用都是内核实现框架完成的.所以程序员只 ...