四.对象关系映射-part3

 

使用 XML 映射


JPA 中每一个注解都有一个对应的 XML 标签。 JPA2.0 规范第 12 章覆盖了所有的 XML 标签细节。

配置 XML 会覆盖注解中的值。如果你用某个值注解了一个属性或实体,同时你在 XML 部署描述符中配置了另一个值,那么,会采用 XML 中的值。


 

例:

 

@Entity
public class Book {
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private Long id;
	private String title;
	private Float price;
	@Column(length = 500)
	private String description;
	private String isbn;
	private Integer nbOfPage;
	private Boolean illustrations;
	// Constructors, getters, setters
}

 

 

META-INF/book_mapping.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm
http://java.sun.com/xml/ns/persistence/orm_2_0.xsd"
	version="2.0">
	
	<entity class="org.example.myproject.model.Book">
		<table name="book_xml_mapping" />
		<attributes>
			<basic name="title">
				<column name="book_title" nullable="false" updatable="false" />
			</basic>
			<basic name="description">
				<column length="2000" />
			</basic>
			<basic name="nbOfPage">
				<column name="nb_of_page" nullable="false" />
			</basic>
		</attributes>
	</entity>
	
</entity-mappings>

 

persistence.xml 部分代码:

 

<persistence-unit name="primary">
		
		<provider>org.hibernate.ejb.HibernatePersistence</provider>
		<mapping-file>META-INF/book_mapping.xml</mapping-file>
		<class>org.example.myproject.model.Book</class>
		...
		
</persistence-unit>	

 

 

最后是 XML 元数据和注解元数据的合并映射结果,产生的 DDL

 

CREATE TABLE `book_xml_mapping` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `description` longtext,
  `illustrations` bit(1) DEFAULT NULL,
  `isbn` varchar(255) DEFAULT NULL,
  `nb_of_page` int(11) NOT NULL,
  `price` float DEFAULT NULL,
  `book_title` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
)
 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值