Hibernate使用Annotation的一对多:


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"/> </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 java.util.Set; import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table; @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; @OneToMany(mappedBy="user", cascade=CascadeType.ALL)
private Set<UserCard> cards; 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 Set<UserCard> getCards() {
return cards;
} public void setCards(Set<UserCard> cards) {
this.cards = cards;
}
}
package com.my.bean;

import javax.persistence.CascadeType;
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.ManyToOne;
import javax.persistence.Table; @Entity
@Table(name="user_card")
public class UserCard {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="card_id")
private long cardID; @Column(name="card_name")
private String CardName; @ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name="user_id")
private User user; public long getCardID() {
return cardID;
}
public void setCardID(long cardID) {
this.cardID = cardID;
}
public String getCardName() {
return CardName;
}
public void setCardName(String cardName) {
CardName = cardName;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}

测试:

package com.my.init;
import java.util.Date;
import java.util.HashSet; import org.hibernate.Session;
import org.hibernate.Transaction; import com.my.bean.User;
import com.my.bean.UserCard;
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 {
//---------------------------------------------------
// add user
//---------------------------------------------------
User user = new User();
user.setUserName("Robin");
user.setCreateTime(new Date());
user.setCards(new HashSet<UserCard>()); //---------------------------------------------------
// add card
//---------------------------------------------------
UserCard cardBBC = new UserCard();
cardBBC.setCardName("BCC");
cardBBC.setUser(user);
UserCard cardCBC = new UserCard();
cardCBC.setCardName("CBC");
cardCBC.setUser(user); // add cards to user
user.getCards().add(cardBBC);
user.getCards().add(cardCBC); //---------------------------------------------------
// save
//--------------------------------------------------
session.save(user); //---------------------------------------------------
// remove user
//---------------------------------------------------
session.delete(user); tx.commit();
} catch (Exception e) {
tx.rollback();
e.printStackTrace();
} session.close();
} }

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

  1. [Hibernate] - Annotations - Many To Many

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

  2. [Hibernate] - Annotations - One To One

    Hibernate annotation 一对一的两种实现: 1)幅表中有主表的主键ID做为引用 2)幅表的主键即为主表的ID hibernate.cfg.xml <?xml version=& ...

  3. 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 ...

  4. 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 ...

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

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

  6. BAE 环境下 hibernate annotations 配置

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

  7. 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 ...

  8. Hibernate Annotations 注解

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

  9. [Hibernate] - Annotations

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

随机推荐

  1. iOS开发环境C语言基础 运算符和表达式

    1 年龄判断程序 1.1 问题 本案例需要使用交互的方式判断年龄的范围:用户从控制台输入一个年龄,由程序判断该年龄是否在18~50岁之间.程序交互过程如图-1所示: 图-1 1.2 步骤 实现此案例需 ...

  2. 101+ Manual and Automation Software Testing Interview Questions and Answers

    101+ Manual and Automation Software Testing Interview Questions and Answers http://www.softwaretesti ...

  3. VirtualBox 设置共享文件夹自动挂载

    1.在VirtualBox中设置文件夹位置和名称,这里使用的名称是share 1.在ubuntu12.04的/etc/rc.local中加入自动挂载命令 sudo mount -t vboxsf sh ...

  4. 博客Mac桌面编辑器-cnblogs

    Mac篇 公司的机器内存只有8G,不想再大动干戈为了Windows Live Writer装个Vmware了,谷歌娘讲MarsEdit不错,那就试试用这个写个试用贴呗   就是这货了,果然是火星来的, ...

  5. codeforce The Art of Dealing with ATM

    题目大意 ATM取款机有n种不同的钱币kind[i],每次取款允许吐出不超过k张钱币,且钱币的种类数不能超过2(一开始没理解2的意思),现在有q次取款,钱数为ques,问ATM能否凑出这样的钱,若能的 ...

  6. Java-->一个只能运行十次的程序

    --> 感觉没什么营养的样子啊... package com.dragon.java.tensoftware; import java.io.BufferedReader; import jav ...

  7. 常用tcode

    SAP常用TCODE 1 MMBE 查询库存 2 CO01 生产订单创建 3 ME2N-按采购订单编号 ME2B/ME2M/ME2C/ME2W 采购订单查询 清单范围ALV 4 MB51 物料凭证清单 ...

  8. hdu 2680 最短路径(dijkstra算法+多源最短路径单源化求最小值)这题有点意思

    Choose the best route Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Ot ...

  9. sgu259 Printed PR    贪心

    link:http://acm.sgu.ru/problem.php?contest=0&problem=259 思路就是贪心. 首先要读懂题目,输入的方式,把样例读懂. 第一,打印的总时间一 ...

  10. Ubuntu安装Mysql+Django+MySQLdb

    安装Mysql sudo apt-get install mysql-server mysql-client root@IdeaPad:/# mysql -u root -p Enter passwo ...