




已阅读5页,还剩27页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
hibernate annotation 双向 one-to-one 注解 环境:Hibernate 3.3.1 Maven 3.0.4 MySQL 5.5.13 Myeclipse 8.6.1 建表语句:DROP TABLE IF EXISTS t_card;CREATE TABLE t_card ( cardId int(10) unsigned NOT NULL AUTO_INCREMENT, cardNumber char(18) NOT NULL, PRIMARY KEY (cardId) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=gb2312;INSERT INTO t_card VALUES (1,;DROP TABLE IF EXISTS t_person;CREATE TABLE t_person ( personId int(10) unsigned NOT NULL AUTO_INCREMENT, personName varchar(15) NOT NULL, cid int(10) unsigned NOT NULL, PRIMARY KEY (personId) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=gb2312;INSERT INTO t_person VALUES (1, fancy, 1);Person.javapackage com.fancy.po;import javax.persistence.CascadeType;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;/* * - * 文件: Person.java * 作者: fancy * 邮箱: * 时间: 2012-6-10 * 描述: 实体类 * - */* * Entity 声明一个类为实体Bean * Table(name = xx)指定实体类映射的表,如果表名和实体类名一致,可以不指定 */EntityTable(name = t_person)public class Person private Integer personId; private String personName; private Card card; /* * Id 映射主键属性,这里采用uuid的主键生成策略 * GeneratedValue 注解声明了主键的生成策略。该注解有如下属性 * strategy 指定生成的策略,默认是GenerationType. AUTO * GenerationType.AUTO 主键由程序控制 * GenerationType.TABLE 使用一个特定的数据库表格来保存主键 * GenerationType.IDENTITY 主键由数据库自动生成,主要是自动增长类型 * GenerationType.SEQUENCE 根据底层数据库的序列来生成主键,条件是数据库支持序列 * generator 指定生成主键使用的生成器 */ Id GeneratedValue(strategy = GenerationType.AUTO) public Integer getPersonId() return personId; /* * OneToOne:一对一关联 * cascade:级联,它可以有有五个值可选,分别是: * CascadeType.PERSIST:级联新建 * CascadeType.REMOVE : 级联删除 * CascadeType.REFRESH:级联刷新 * CascadeType.MERGE : 级联更新 * CascadeType.ALL : 以上全部四项 * JoinColumn:主表外键字段 * cid:Person所映射的表中的一个字段 */ OneToOne(cascade = CascadeType.ALL) JoinColumn(name = cid) public Card getCard() return card; public String getPersonName() return personName; public void setPersonId(Integer personId) this.personId = personId; public void setPersonName(String personName) this.personName = personName; public void setCard(Card card) this.card = card; Card.javapackage com.fancy.po;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;import javax.persistence.OneToOne;import javax.persistence.Table;/* * - * 文件: Card.java * 作者: fancy * 邮箱: * 时间: 2012-6-10 * 描述: 实体类 * - */EntityTable(name = t_card)public class Card private Integer cardId; private String cardNumber; private Person person; Id GeneratedValue(strategy = GenerationType.AUTO) public Integer getCardId() return cardId; /* * OneToOne:一对一关联 * mappedBy = card:意思是说这里的一对一配置参考了card * card又是什么呢?card是Person类中的getCard(),注意不是Person类中的 * card属性,Person类中的OneToOne配置就是在getCard()方法上面配的. * 如果Person类中的getCard()方法改成getIdCard(),其他不变的话, * 这里就要写成:mappedBy = idCard */ OneToOne(mappedBy = card) public Person getPerson() return person; public String getCardNumber() return cardNumber; public void setCardId(Integer cardId) this.cardId = cardId; public void setCardNumber(String cardNumber) this.cardNumber = cardNumber; public void setPerson(Person person) this.person = person; pom.xml 4.0.0 com.fancy hibernate-annotation-on-to-one-example 0.0.1-SNAPSHOT jar hibernate-annotation-on-to-one-example UTF-8 org.hibernate hibernate-entitymanager 3.3.1.ga org.hibernate hibernate-annotations 3.3.1.GA mysql mysql-connector-java 5.1.17 junit junit 3.8.1 test 在生成数据库表的过程中,报javax.persistence.OneToMany.orphanRemoval()Z异常的解决方法:去掉myeclipse中的j2ee包居然就可以了!oneToMany(mappedBy=另一方类中对应的属性名(外键),cascade=CascadeType.ALL,fetch=FetchType.EAGER)就相当于xml配置中的inverse=true在单向关系中没有mappedBy。mappedBy一定是定义在the owned side(被拥有方的),他指向the owning side(拥有方);主控方相当于拥有指向另一方的外键的一方。mappedBy指定的是不需要维护关系的一端ManyToOneJoinColumn(name=外键的字段名)1.一对一和多对一的JoinColumn注解的都是在“主控方”,都是本表指向外表的外键名称。2.一对多的JoinColumn注解在“被控方”,即一的一方,指的是外表中指向本表的外键名称。3.多对多中,joinColumns写的都是本表在中间表的外键名称, inverseJoinColumns写的是另一个表在中间表的外键名称。mappedBy跟JoinColumn/JoinTable总是处于互斥的一方如产品类型和产品的关系:EntityTable(name=tb_productType)/经常给漏掉这东西public class ProductType extends BaseBean private static final long serialVersionUID = 3466104768256418884L;Column(nullable=false,unique=true)private String name;OneToMany(mappedBy=type,cascade=CascadeType.ALL,fetch=FetchType.EAGER)private List products;.和:EntityTable(name=tb_product)public class Product extends BaseBean private static final long serialVersionUID = 4109238647414563541L;Column(nullable=false)private String name;Column(precision=2)private double price;Basic(fetch = FetchType.LAZY)Column(columnDefinition = longtext)private String intro;private String masterDrowing;ManyToOneJoinColumn(name=productType_id)private ProductType type;private String comment;private int hit;private boolean finalRealse;private int count;ManyToOneJoinColumn(name=person_id)private Person contacter;Temporal(value = TemporalType.DATE)private Date realseDate;.hibernate的配置文件:com.mysql.jdbc.Driverjdbc:mysql:/localhost:3306/site?characterEncoding=UTF-8rootrootorg.hibernate.dialect.MySQLDialecttruecreatethread产生数据库表的类:createTable类import org.hibernate.cfg.AnnotationConfiguration;import org.hibernate.tool.hbm2ddl.SchemaExport;public class CreateTable static void create()SchemaExport export = new SchemaExport(new AnnotationConfiguration().configure(); export.create(true, true);public static void main(String args)create();经过这些配置就可以生成数据库表了!单向关系中的JoinColumn 1.person与address的一对一单向关系:在address中没有特殊的注解。在Person中对应到数据库里面就有一个指向Address的外键.我们也可以增加注释指定外键的列的名字,如下: OneToOne(cascade=CascadeType.ALL,optional=true) JoinColumn(name=addressID)/注释本表中指向另一个表的外键。 public Address getAddress() return address; 如果我们不加的话,也是可以通过的,在JBOSS里面,它会自动帮你生成你指向这个类的类名加上下划线再加上id的列,也就是默认列名是:address_id. 如果是主键相关联的话,那么可以运用如下注释 OneToOne(cascade=CascadeType.ALL) PrimaryKeyJoinColumn public Address getAddress( ) return homeAddress; 它表示两张表的关联是根据两张表的主键的2.person和phone的一对多单向关系:phone中没有特别的注释。person中:OneToMany(cascade=CascadeType.ALL)JoinColumn(name=personID)/注释的是另一个表指向本表的外键。public List getPhones() return phones; 我们可以在Person类里面发现JoinColumn(name=personID) 它代表是一对多,一是指类本身,多是指这个成员,也就是一个类可以对应多个成员. 在一对多里面,无论是单向还是双向,映射关系的维护端都是在多的那一方,也就是Phone那里,因为要在数据库面表现的话,也只有让Phone起一个指向Person的外键,不可能在Person里面指向Phone,这一点和一对一不一样,一对一可以在任意一方起一个外键指向对方.可是一对多却不行了.在这里JoinColumn这个注释指的却是在Phone里面的外键的列的名字,它并不像在一对一里面的注释指的是自己表里面的外键列名.这一点要特别注意一下.如果是一对多的双向关系,那么这个注释就要应用到多的那边去了,虽然注释还在Person类里面,但是它起的效果却是在Phone里面起一个叫personID的外键, 因为多的那边要有外键指向少的这边. 如果你不加 JoinColumn(name=personID)这个注释的话,那么JBOSS就会自动帮你生成一张中间表,它负现Person和Phone表之间的联系.它将会做如下事情:CREATE TABLE PERSON_PHONE( PERSON_id INT, PHONE_id INT);ALTER TABLE PERSON_PHONE ADD CONSTRAINT person_phone_unique UNIQUE (PHONE_id);ALTER TABLE PERSON_PHONE ADD CONSTRAINT personREFphone FOREIGN KEY (PERSON_id) REFERENCES PERSON (id);ALTER TABLE PERSON_PHONE ADD CONSTRAINT personREFphone2 FOREIGN KEY (PHONE_id) REFERENCES PHONE (id);所以我们最好还是指定一下,以让程序产生更加确定的行为,不过一般是推荐另外生成一个中间表好一些,因为这样的话,对原来两张表的结构不对造成任何影响。在遗留系统的时候很多用,有些时候,一些表都是以前就建好了的,要改表的结构是不太可能的,所以这个时候中间的表就显得很重要了,它可以在不侵入原来表的情况下构建出一种更清淅更易管理的关系。所以一对多的单向关联,我们还是推荐使用一张中间表来建立关系。-3.person和country的多对一单向关系:country中无特别的注解。而person注解如下:ManyToOneJoinColumn(name=countryID) public Country getCountry() return country; 在一对多一对多一对的关系里面,关系的维护端都是在多的那一面,多的一面为主控方,拥有指向对方的外键。因为主控端是Person .外键也是建在Person上面,因为它是多的一面。当然我们在这里也可以省掉JoinColumn,那样的话会怎么样呢,会不会像一对多单向一样生成中间的表呢?事实是不会的,在这里如果我们去掉JoinColumn的话,那么一样会在Person表里面生成一列指向Country的外键,这一点和一对多的单向是不一样,在一对多的单向里面,如果我们不在Person 里面加上JoinColumn这个注释,那么JBOSS将会为我们生成一个中间的表,这个表会有一个列指向Person主键,一个列指向Phone主键。所以说为了程序有一定的行为,有些东西我们还是不要省的好。 其实多对一单向是有点向一对一单向的,在主控端里面,也就是从Person的角度来看,也就是对应了一个Country而已,只不过这个Country是很多Person所共用的,而一对一却没有这一点限制。 4.person和project的多对多单向关系:project没有特殊的注解。person:ManyToMany public List getProjects() return projects; 它需要设置中间表来维护关系,在数据库上跟多对多双向,只不过在编程的逻辑中不一样而已。/类似这个:JoinTable(name = PersonANDFlight, joinColumns = JoinColumn(name = personID), /inverseJoinColumns = JoinColumn(name = flightID)其实这个声明不是必要的,当我们不用JoinTable来声明的时候,JBOSS也会为我们自动生成一个连接用的表,表名默认是主控端的表名加上下划线_再加上反转端的表名.类似ManyToMany(cascade = CascadeType.ALL) JoinTable(name = PersonANDFlight, joinColumns = JoinColumn(name = personID), inverseJoinColumns = JoinColumn(name = flightID) public List getFlights() return flights; 在单向关系中没有mappedBy,主控方相当于拥有指向另一方的外键的一方。1.一对一和多对一的JoinColumn注解的都是在“主控方”,都是本表指向外表的外键名称。2.一对多的JoinColumn注解在“被控方”,即一的一方,指的是外表中指向本表的外键名称。3.多对多中,joinColumns写的都是本表在中间表的外键名称, inverseJoinColumns写的是另一个表在中间表的外键名称。使用 OneToOne 注解可以建立实体bean之间的一对一的关联。一对一关联有两种情况:一是关联的实体都共享同样的主键,二是其中一个实体通过外键关联到另一个实体的主键(注意要模拟一对一关联必须在外键字段上添加唯一性约束).First, we map a real one-to-one association using shared primarykeys:首先,我们通过共享主键来进行一对一关联映射:Entitypublic class Body Idpublic Long getId() return id; OneToOne(cascade = CascadeType.ALL)PrimaryKeyJoinColumnpublic Heart getHeart() return heart;.Entitypublic class Heart Idpublic Long getId() .The one to one is marked as true by using thePrimaryKeyJoinColumn annotation.通过使用 PrimaryKeyJoinColumn 注解定义了一对一关联。In the following example, the associated entities are linkedthrough a foreign key column:下面这个例子使用外键进行实体的关联。Entitypublic class Customer implements Serializable OneToOne(cascade = CascadeType.ALL)JoinColumn(name=passport_fk) public Passport getPassport() .Entitypublic class Passport implements Serializable OneToOne( mappedBy = passport )public Customer getOwner() .A Customer is linked to aPassport , with a foreign key column named?passport_fk in the Customer ? table. The join column is declared with theJoinColumn annotation which looks like theColumn annotation. It has one more parametersnamed referencedColumnName . This parameter declaresthe column in the targeted entity that will be used to the join. Notethat when using? referencedColumnName ? to a non? primary key column, the associated class has to beSerializable . Also note that the? referencedColumnName ? to a non? primary key column has to be mapped to a property having a singlecolumn (other cases might not work).上面这个例子中, Customer 通过 Customer 表中名为的 passport_fk 外键和 Passport 关联。JoinColumn 注解定义了关联字段。该注解和 Column 注解有点类似,但是多了一个名为 referencedColumnName 的参数。该参数定义了所关联目标实体中的关联字段。注意,当 ? ?referencedColumnName ? 关联到非主键字段的时候,? 关联的目标类必须实现 Serializable ,还要注意的是所映射的属性只有单个字段(否则映射无效)。.The association may be bidirectional. In a bidirectionalrelationship, one of the sides (and only one) has to be the owner: theowner is responsible for the association column(s) update. To declarea side as not responsible for the relationship,the attribute mappedBy is used.mappedBy refers to the property name of theassociation on the owner side. In our case, this ispassport . As you can see, you dont have to (mustnot) declare the join column since it has already been declared on theowners side.一对一关联可能是双向的。在双向关联中,有且仅有一端是作为owner存在的:owner负责维护关联字段(即更新)。对于不需要维护这种关系的一端则通过mappedBy属性进行声明。mappedBy 的值指向owner端的关联属性。在上面这个例子中, ?mappedBy 的值为 passport 。? 最后,不必也不能再在另外一端(非owner端)定义关联字段了,因为已经在owner端进行了声明。If no JoinColumn is declared on the ownerside, the defaults apply. A join column(s) will be created in theowner table and its name will be the concatenation of the name of therelationship in the owner side, _ (underscore), andthe name of the primary key column(s) in the owned side. In thisexample passport_id because the property name ispassport and the column id of Passport ? is id .如果在owner端没有声明 JoinColumn ,系统自动进行处理:在owner表中将创建关联字段,字段名为:owner端的关联属性名下划线被关联端的主键字段名。在上面这个例子中是 passport_id ,因为 ?Customer 中关联属性名为 passport ,? ?Passport 的主键是 id 。? Many-to-oneMany-to-one associations are declared at the property level withthe annotation ManyToOne :在实体属性一级使用 ManyToOne 注解来定义多对一关联:Entity()public class Flight implements Serializable ManyToOne ( cascade = CascadeType.CREATE, CascadeType.MERGE )JoinColumn(name=COMP_ID)public Company getCompany() return company;.The JoinColumn attribute is optional, thedefault value(s) is like in one to one, the concatenation of the nameof the relationship in the owner side, _(underscore), and the name of the primary key column in the ownedside. In this example company_id because theproperty name is company and the column id ofCompany is id .其中 JoinColumn 是可选的,关联字段默认值和一对一(one to one)关联的情况相似,也是owner端的关联属性名下划线被关联端的主键字段名。在这个例子中是 company_id ,因为关联的属性是 company ,?Company 的主键是 id 。? ManyToOne has a parameter namedtargetEntity which describes the target entityname. You usually dont need this parameter since the default value(the type of the property that stores the association) is good inalmost all cases. However this is useful when you want to useinterfaces as the return type instead of the regular entity.?ManyToOne 注解有一个名为 targetEntity 的参数,? 该参数定义了目标实体名。通常不需要定义该参数,因为在大部分情况下默认值(表示关联关系的属性类型)就可以很好的满足要求了。不过下面这种情况下这个参数就显得有意义了:使用接口作为返回值而不是常见的实体。Entity()public class Flight implements Serializable ManyToOne( cascade = CascadeType.CREATE, CascadeType.MERGE, targetEntity=CompanyImpl.class )JoinColumn(name=COMP_ID)public Company getCompany() return company;.public interface Company .CollectionsOverviewYou can map Collection ,List (ie ordered lists, not indexed lists),Map and Set . The EJB3specification describes how to map an ordered list (ie a listordered at load time) usingjavax.persistence.OrderBy annotation: thisannotation takes into parameter a list of comma separated (targetentity) properties to order the collection by (eg firstnameasc, age desc), if the string is empty, the collection willbe ordered by id. OrderBy currently works onlyon collections having no association table. For true indexedcollections, please refer to the .EJB3 allows you to map M
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2025年G2电站锅炉司炉理论考试题及答案
- 口才考试题及答案
- 钢筋考试题及答案
- 中华传统文化知到智慧树答案
- 药品知识竞赛考试题目及答案
- 中西医临床骨伤科学(运动健康与创伤防治)知到智慧树答案
- 中学生物学教学论知到智慧树答案
- 公需科目考试试题及答案
- 2025版清尾款支付与产品验收标准合同范本
- VR技能考核系统设计-洞察及研究
- 学习2025年初中初三开学第一课专题
- 2023年浙江省金华婺城区新闻传媒中心诚聘合同制融媒体采编人员高频考点题库(共500题含答案解析)模拟练习试卷
- 世界社会主义五百年
- IVF实验室质量控制与质量保障
- GB/T 2820.4-2009往复式内燃机驱动的交流发电机组第4部分:控制装置和开关装置
- GB/T 13762-2009土工合成材料土工布及土工布有关产品单位面积质量的测定方法
- 生活离不开规则观课报告
- 石灰石-石膏湿法脱硫化学分析课件
- 个人房地产抵押合同书
- 医院零星维修管理制度及零星维修审批单
- 住院医师规范化培训申请表
评论
0/150
提交评论