使用 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`)
)