Hibernate,JPA注解@OneToOne_JoinColumn
一对一(One-to-one),外键关联
用例代码如下:
- 数据库DDL语句
1,CAT表
create table CAT
(
id VARCHAR2(32 CHAR) not null,
create_time TIMESTAMP(6),
update_time TIMESTAMP(6),
cat_name VARCHAR2(255 CHAR),
first_name VARCHAR2(255 CHAR),
last_name VARCHAR2(255 CHAR),
version NUMBER(10) not null
)
2,CAT_INFO表
create table CAT_INFO
(
id VARCHAR2(32 CHAR) not null,
create_time TIMESTAMP(6),
update_time TIMESTAMP(6),
address VARCHAR2(255 CHAR),
birthday TIMESTAMP(6),
cat_id VARCHAR2(32 CHAR)
)
- hibernate.cfg.xml
<?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.Oracle10gDialect</property>
<property name="connection.driver_class">oracle.jdbc.OracleDriver</property>
<property name="connection.url">jdbc:oracle:thin:@127.0.0.1:1521:orcl</property>
<property name="connection.username">wxuatuser</property>
<property name="connection.password">xlh</property>
<property name="show_sql">true</property>
<!-- 自动执行DDL属性是update,不是true -->
<property name="hbm2ddl.auto">update</property>
<!-- hibernate实体类 --> <mapping class="a7_OneToOne_JoinColumn.Cat"/>
<mapping class="a7_OneToOne_JoinColumn.Cat_Info"/> </session-factory>
</hibernate-configuration>
- java类
实体类 - 基类
package model;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import org.hibernate.annotations.GenericGenerator;
/**
* 实体类 - 基类
*/
@MappedSuperclass
public class BaseEntity implements Serializable { private static final long serialVersionUID = -6718838800112233445L; private String id;// ID
private Date create_time;// 创建日期
private Date update_time;// 修改日期
@Id
@Column(length = 32, nullable = true)
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Column(updatable = false)
public Date getCreate_time() {
return create_time;
}
public void setCreate_time(Date create_time) {
this.create_time = create_time;
}
public Date getUpdate_time() {
return update_time;
}
public void setUpdate_time(Date update_time) {
this.update_time = update_time;
}
@Override
public int hashCode() {
return id == null ? System.identityHashCode(this) : id.hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass().getPackage() != obj.getClass().getPackage()) {
return false;
}
final BaseEntity other = (BaseEntity) obj;
if (id == null) {
if (other.getId() != null) {
return false;
}
} else if (!id.equals(other.getId())) {
return false;
}
return true;
}
}
实体类
Cat.java
package a7_OneToOne_JoinColumn;
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Version;
import model.BaseEntity;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate; @Entity
@DynamicInsert
@DynamicUpdate
public class Cat extends BaseEntity{
/**
* 实体类
*/
private static final long serialVersionUID = -2776330321385582872L; private Cat_Info cat_Info; private String cat_name;
private Name name;
private int version; @Version
public int getVersion() {
return version;
} public void setVersion(int version) {
this.version = version;
} public String getCat_name() {
return cat_name;
} public void setCat_name(String cat_name) {
this.cat_name = cat_name;
} @Embedded
@AttributeOverrides({
@AttributeOverride(name = "first_name", column = @Column(name = "first_name")),
@AttributeOverride(name = "last_name", column = @Column(name = "last_name")) })
public Name getName() {
return name;
} public void setName(Name name) {
this.name = name;
} /*
* mappedBy属性:
* 如果关系是单向的,则该关联提供程序确定拥有该关系的字段。
* 如果关系是双向的,则将关联相反(非拥有)方上的 mappedBy 元素设置为拥
* 有此关系的字段或属性的名称
*/
@OneToOne(cascade = CascadeType.ALL,mappedBy="cat")
@JoinColumn(name="id", referencedColumnName="id", unique=true, nullable=false, updatable=true)
public Cat_Info getCat_Info() {
return cat_Info;
} public void setCat_Info(Cat_Info cat_Info) {
this.cat_Info = cat_Info;
}
}
Cat_Info.java
package a7_OneToOne_JoinColumn;
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.OneToOne;
import model.BaseEntity; @Entity
public class Cat_Info extends BaseEntity{
/**
*
*/
private static final long serialVersionUID = 8258082211095664606L; private Cat cat;
private String address;
private Date birthday; public String getAddress() {
return address;
} public void setAddress(String address) {
this.address = address;
} public Date getBirthday() {
return birthday;
} public void setBirthday(Date birthday) {
this.birthday = birthday;
} @OneToOne(cascade = {CascadeType.ALL},fetch = FetchType.EAGER)
public Cat getCat() {
return cat;
} public void setCat(Cat cat) {
this.cat = cat;
}
}
组件类
package a7_OneToOne_JoinColumn;
import java.io.Serializable;
import javax.persistence.Embeddable; @Embeddable
public class Name implements Serializable {
/**
* 嵌入式组建
*/
private static final long serialVersionUID = -2776330321385582872L; private String first_name;
private String last_name;
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
}
Dao
package daoUtil;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder; public class HibernateUtil { private static final SessionFactory sessionFactory; static {
try {
Configuration cfg = new Configuration().configure();
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
.applySettings(cfg.getProperties()).buildServiceRegistry();
sessionFactory = cfg.buildSessionFactory(serviceRegistry);
} catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
} public static Session getSession() throws HibernateException {
return sessionFactory.openSession();
} public static Object save(Object obj){
Session session = HibernateUtil.getSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
session.save(obj);
tx.commit();
} catch (RuntimeException e) {
if (tx != null) {
tx.rollback();
}
throw e;
} finally {
session.close();
}
return obj;
} public static void delete(Class<?> clazz,String id){
Session session = HibernateUtil.getSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Object obj = session.get(clazz,id);
session.delete(obj);
tx.commit();
} catch (RuntimeException e) {
if (tx != null) {
tx.rollback();
}
throw e;
} finally {
session.close();
}
}
}
main
package a7_OneToOne_JoinColumn;
import java.util.Date;
import daoUtil.HibernateUtil; public class Test_OneToOne_JoinColumn { private Cat save(){ Cat_Info info = new Cat_Info();
info.setAddress("201503291");
info.setBirthday(new Date()); Cat cat = new Cat();
cat.setCat_name("a7_OneToOne_JoinColumn");
cat.setName(new Name());
cat.setCat_Info(info);
info.setCat(cat); HibernateUtil.save(info);
System.out.println(cat.getId());
return cat;
} public static void main(String[] args) { Cat cat = new Test_OneToOne_JoinColumn().save();
Cat cat1 = (Cat)HibernateUtil.getSession().get(Cat.class, cat.getId());
System.out.println(cat1.getId()); Cat_Info cat_Info = (Cat_Info)HibernateUtil.getSession().get(Cat_Info.class, cat1.getCat_Info().getId());
System.out.println(cat_Info.getId());
}
}
环境:JDK1.6,MAVEN,tomcat,eclipse
源码地址:http://files.cnblogs.com/files/xiluhua/hibernate%40OneToOne_JoinColumn.rar
Hibernate,JPA注解@OneToOne_JoinColumn的更多相关文章
- Java、Hibernate(JPA)注解大全
1.@Entity(name=”EntityName”) 必须,name为可选,对应数据库中一的个表 2.@Table(name=””,catalog=””,schema=””) 可选,通常和@Ent ...
- hibernate jpa 注解 @Temporal(TemporalType.DATE) 格式化时间日期,页面直接得到格式化类型的值
1.日期: @Temporal(TemporalType.DATE) @Column(name = "applyDate", nullable = false, length = ...
- 【hibernate/JPA】注解方式实现 复合主键【spring boot】
1>hibernate/JPA实现复合主键的思路:是将所有的主键属性封装在一个主键类中,提供给需要复合主键的实体类使用. 2>主键类的几点要求: . 使用复合主键的实体类必须实现Seria ...
- hibernate自带的注解和jpa注解的冠希
hibernate是实现了JPA规范,在我们使用hibernate框架的时候,我们引入了hibernate3或者4这个核心包.hibernate-jpa-2.0-api-1.0.0.Final.jar ...
- Hibernate 和 JPA 注解
转载请注明:Hibernate 和 JPA 注解 | 言曌博客 1.@Entity(name="EntityName") 必须, name为可选,对应数据库中一的个表 2.@Tab ...
- jpa 注解使用说明
1.@Entity(name="EntityName") 必须,name为可选,对应数据库中一的个表 2.@Table(name="",catalog=&quo ...
- Hibernate基于注解方式配置来实现实体和数据库之间存在某种映射关系
实体和数据库之间存在某种映射关系,hibernate根据这种映射关系完成数据的存取.在程序中这种映射关系由映射文件(*.hbm.xml)或者java注解(@)定义. 本文以java注解的形式总结映射关 ...
- Hibernate+JPA (EntityMange讲解)
近年来ORM(Object-Relational Mapping)对象关系映射,即实体对象和数据库表的映射)技术市场人声音鼎沸,异常热闹, Sun在充分吸收现有的优秀ORM框架设计思想的基础上,制定了 ...
- spring+hibernate+jpa+Druid的配置文件,spring整合Druid
spring+hibernate+jpa+Druid的配置文件 spring+hibernate+jpa+Druid的完整配置 spring+hibernate+jpa+Druid的数据源配置 spr ...
随机推荐
- sql server 还原数据库时提示数据库正在使用,无法进行操作的解决方法
这个问题的原因在于有用户连接了当前要做还原的数据库,这里的用户甚至包括当前要做还原的用户.解决办法就是关闭与要还原数据库的所有连接. 脚本之家小编推荐的一个方法:到服务里面重启下sqlserver服务 ...
- 4、JavaScript进阶篇①——基础语法
一.认识JS 你知道吗,Web前端开发师需要掌握什么技术?也许你已经了解HTML标记(也称为结构),知道了CSS样式(也称为表示),会使用HTML+CSS创建一个漂亮的页面,但这还不够,它只是静态页面 ...
- git 查看、创建、删除 本地,远程 分支
1. 查看远程分支 git branch -rorigin/master 2. 查看本地分支 git branch *master 注:以*开头指明现在所在的本地分支 3. 查看本地分支和远程分支 g ...
- CentOS下netstat + awk 查看tcp的网络连接状态
执行以下命令: #netstat -n | awk ‘/^tcp/ {++state[$NF]} END {for(key in state) print key."\t".sta ...
- Visual Studio Debugger AutoExp.dat & Visualization Framework
bing.com搜索: autoexp.dat 参考资料: AutoExp.dat http://www.virtualdub.org/blog/pivot/entry.php?id=120 http ...
- Springfox Reference Documentation
1. Introduction The Springfox suite of java libraries are all about automating the generation of mac ...
- Java Axis2 1.6.3+JDK1.7.0_13+Tomcat7.0.65+eclipse搭建web service
安装文件下载: jdk1.7.0_13 安装步骤参考文章:http://jingyan.baidu.com/article/6dad5075d1dc40a123e36ea3.html tomcat7. ...
- Android遇到的错误,运行时崩溃
修改主题背景时在<Activity>中增加android:theme="@android:style/Theme.Black.NoTitleBar"时运行 出现崩溃的现 ...
- Java基础(2):Java中的四个跳转语句总结goto,break,continue,return
跳转控制语句 Java中的goto是保留字,目前不能使用.虽然没有goto语句可以增强程序的安全性,但是也带来很多不便,比如说,我想在某个循环知道到某一步的时候就结束,现在就做不了这件事情.为了弥补这 ...
- WEB-INF/views/menu/list.jsp (line: 26, column: 58) equal symbol expected
根本原因是由于单引号和双引号的混乱使用导致的. 解决办法: 将双引号里面的双引号改成单引号: 单引号里面的双引号该成单引号. 我的问题好像又不是这样的,<c:forEach var=" ...